没有得到所需的输出
问题描述:
我不明白为什么当程序被循环条件终止时,我得到了下一个元素的输出。如果我输入3,程序终止询问第三个值,但没有输入任何内容。当您使用in.nextInt()
它只读取从输入流的整数值有什么问题没有得到所需的输出
Scanner in = new Scanner(System.in);
System.out.println("number of word you want to input");
int NumberOfWord = in.nextInt();
System.out.println("input the words-->");
for (int i = 0; i <= NumberOfWord; i++) {
userInput[i] = in.nextLine();
System.out.println("enter your "+(i+1)+"th word");
答
。但它不会读取之后出现的换行符。
在循环中调用nextLine()
方法之前,可以使用虚拟的in.nextLine()
,该方法用于读取整数值后面的换行符。
int NumberOfWord = in.nextInt();
in.nextLine();
System.out.println("input the words-->");
for (int i = 0; i < NumberOfWord; i++) {
userInput[i] = in.nextLine();
System.out.println("enter your " + (i + 1) + "th word");
}
另一种解决方法是使用nextLine()
方法本身来读取整数值。 nextLine()
方法从流中读取整行,以换行符作为终止点(也包括换行符)。因此,需要在使用nextInt()
int NumberOfWord = Integer.parseInt(in.nextLine());
System.out.println("input the words-->");
for (int i = 0; i < NumberOfWord; i++) {
userInput[i] = in.nextLine();
System.out.println("enter your " + (i + 1) + "th word");
}
而且在你的循环条件,其中使用<=
这将要求一个更高的价值为你的循环是从0
'nextInt开始(这是发生问题的护理)'在输入的数字后面结束,并且需要另一个'nextLine()'来完成该行的其余部分(可能为空)... –
正确声明userInput。它是未定义的。 – Tehmina