-1
package scanner;
import java.util.Scanner;

public class GuessSentence {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Type a sentence");
        String sentence = sc.nextLine();
        System.out.println("You entered the sentence " + sentence);
        System.out.println("The number of words in the sentence is " + sentence.length());

        char [] chars=sentence.toCharArray();

        int count = 0;
        for (char c : chars) {
            switch(c) {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                count++;
                break;
            }
        }
        System.out.println("The numner of vowels in your sentence is " + count);
        System.out.println("The percentage of vowels is " + 100 * count /sentence.length() + "%" );
    }
}

Thank you to everyone who helped, I was able to get the correct outcome which i was looking for so i appreciate all the help recieved.

ahmed2993
  • 35
  • 7
  • "_However, i do not get the percentage of vowels_" Well, it is there in the output `The percentage of vowels is 2%`. Do you mean that it is just not correct? – takendarkk Nov 21 '18 at 17:36
  • Possible duplicate of [Why is the result of 1/3 == 0?](https://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0) – MWB Nov 21 '18 at 17:38

3 Answers3

2

You want (100.0 * count / sentence.length()). You're using the % operator which is the modulo of two numbers

flakes
  • 12,841
  • 5
  • 28
  • 69
1

When you calculate the percent you do:

sentence.length() % count

But % is the modulo operator, which calculates remainder. You wanted to divide:

sentence.length() / count

However this will still not get you the right results as the scale is not right, and you are dividing incorrectly. It should be:

100 *count / sentence.length()

Or

100.0 *count / sentence.length() 

If you want to avoid truncation

Output:

You entered the sentence Hello World
The number of words in the sentence is 11
The numner of vowels in your sentence is 3
The percentage of vowels is 27%
GBlodgett
  • 12,612
  • 4
  • 26
  • 42
0

You are not using correct operator. modulus(%) gives you the remainder after the division. You need to use division (/) operation. You may want to use double/float for getting accurate value.

Sachin Gupta
  • 3,755
  • 2
  • 13
  • 29