Java 如何找出字符串中元音的百分比?

Java 如何找出字符串中元音的百分比?,java,eclipse,java.util.scanner,Java,Eclipse,Java.util.scanner,感谢所有帮助过我的人,我能够得到我所期待的正确结果,所以我感谢所有得到的帮助 当您计算所做的百分比时: 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

感谢所有帮助过我的人,我能够得到我所期待的正确结果,所以我感谢所有得到的帮助

当您计算所做的百分比时:

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() + "%" );
    }
}
但%是模运算符,它计算余数。你想分开:

sentence.length() % count
但是,这仍然无法获得正确的结果,因为比例不正确,并且分割不正确。应该是:

sentence.length() / count

如果要避免截断

输出:


您需要100.0*计数/句子长度。您使用的是%运算符,它是两个数字的模

您使用的运算符不正确。模数%给出除法后的余数。你需要使用除法/运算法。您可能需要使用double/float来获得准确的值。

但是,我没有很好地获得元音的百分比,它在输出中,元音的百分比是2%。你的意思是它不正确吗?在处理百分比时,它可能重复。通常最好使用浮点100.0而不是整数来避免截断。@flakes不一定。四舍五入到下面的下一个整数可能正是OP想要的。我也相信我需要添加一个浮点,但不知道我将在哪里添加这个,您编写的代码帮助了我,非常感谢you@Satoshi1999你说添加一个浮动是什么意思?没关系,只是做了正确的更改,一切都是正确的,谢谢
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%