gpt4 book ai didi

java - 输入另一个字符串后计算元音和辅音

转载 作者:行者123 更新时间:2023-11-30 01:43:16 25 4
gpt4 key购买 nike

JAVA:

编写一个带有构造函数的类,该构造函数接受 String 对象作为其参数。该类应该有一个返回字符串中元音数量的方法,另一个方法返回字符串中辅音的数量。(空格既不属于元音也不属于辅音,应被忽略。)

在执行以下步骤的程序中演示该类:

  1. 系统会要求用户输入字符串。
  2. 程序显示以下菜单:

a.计算字符串中元音的数量。

b.计算字符串中辅音的数量

c.计算字符串中的元音和辅音

d.输入另一个字符串

e.退出程序

我已经写了代码:你什么时候可以检查我的选项d,当我输入另一个字符串时,它给出的元音和辅音计数为0。

   Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
String input1 = sc.nextLine();

VowelsAndConsonants vc = new VowelsAndConsonants(input1.toLowerCase());

System.out.println("\nWhat would you like to do? Enter:\n" + "'a' to count the vowels\n"
+ "'b' to count consonants\n" + "'c' to count both vowels and consonants\n"
+ "'d' to enter another String\n" + "'e' to exit the program");
char input2 = sc.next().charAt(0);

while (input2 != 'e') {

if (input2 == 'a') {
System.out.println("Vowels: " + vc.vowelsCount());
} else if (input2 == 'b') {
System.out.println("Consonants: " + vc.consonantCount());
} else if (input2 == 'c') {
System.out.println("Vowels: " + vc.vowelsCount());
System.out.println("Consonants: " + vc.consonantCount());
} else if (input2 == 'd') {
System.out.println("Enter another string: ");
input1 = sc.nextLine();
vc = new VowelsAndConsonants(input1.toLowerCase());
}
System.out.println("\nWhat would you like to do? Enter:\n" + "'a' to count the vowels\n"
+ "'b' to count consonants\n" + "'c' to count both vowels and consonants\n"
+ "'d' to enter another String\n" + "'e' to exit the program");
input2 = sc.next().charAt(0);

}
System.out.println("Have a great day!");

最佳答案

当您混合使用 Scannernext()nextLine() 方法时,这是一个众所周知的问题。当您调用 next() 时,它会返回下一个单词,直到换行符,但将换行符保留在缓冲区中。剩余输入的第一行现在是空行。

然后,当您调用 nextLine() 时,它会返回该换行符之前的所有字符;换句话说,它返回零个字符,一个空字符串。

如果您在调用 next() 后小心地通过额外调用 nextLine() 来消耗额外的换行符,nextInt()nextDouble() 等,那么您可以毫无问题地混合调用,但在这种情况下最简单的做法是始终对任何输入使用 nextLine()来自用户。

关于java - 输入另一个字符串后计算元音和辅音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com