当我运行代码时,在输入数字后,它不允许我输入字符串,它会继续



当我输入数字时,它只是向前移动而不让我输入字符串,并显示输出当我使用sc.next((;时;,如果没有字符串,它就无法继续,但我想使用sc.nextLine((,但它不起的作用

public class project1
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int n;
char a;
System.out.println("Enter n 1 for counting the total number of vowels in it n 2 for printing the first letter of each word in a string");
n = sc.nextInt();
switch(n)
{
case 1:
int count = 0;
System.out.println("Input a string");
String str = sc.nextLine();
str = str.toLowerCase();
for(int i = 0; i < str.length(); i++)
{
a = str.charAt(i);
if(a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
count++;
}
System.out.println("There are "+ count +" vowels in the string.");
break;

case 2:
System.out.println("Input a string");
String str2 = sc.nextLine();
System.out.println("First letter of each word:");
for(int i = 0; i < str2.length(); i++)
{
a = str2.charAt(i);
if(a == ' ')
System.out.print(str2.charAt(i+1) + ", "); 
}
break;
}
}
}

sc.nextInt将只读取整数部分,并将其余部分留在输入流中,以供下一个scanner命令使用。因此,当您尝试使用sc.nextLine((.获取字符串输入时,第一个条目中的换行符仍然可用

您可以读取整行并使用将其转换为int

n = Integer.parseInt(sc.nextLine());
switch(n)

或者您可以简单地在sc.nextInt((之后添加一个sc.nextLine((来使用输入行的其余部分。

n = sc.nextInt();
sc.nextLine();
switch(n)

顺便说一下,你写每个单词第一个字母的方法会跳过第一个单词,如果句子以空格结尾,也会崩溃。也许可以试试String.split((。

相关内容

最新更新