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() + "%" );
}
}
感谢所有提供帮助的人,我能够获得想要的正确结果,因此,我感谢收到的所有帮助。
答案 0 :(得分:2)
您想要(100.0 * count / sentence.length())
。您正在使用%
运算符,它是两个数字的模
答案 1 :(得分:1)
计算百分比时,您要做的事:
%
但是sentence.length() / count
是模运算符,用于计算余数。您想划分:
100 *count / sentence.length()
但是,由于比例尺不正确,您仍然无法获得正确的结果,并且您的分配不正确。应该是:
100.0 *count / sentence.length()
或
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%
如果要避免截断
输出:
{{1}}
答案 2 :(得分:0)
您没有使用正确的运算符。模数(%)为您提供除法后的余数。您需要使用除法(/)操作。您可能需要使用double / float来获取准确的值。