为什么这个 for 循环不允许我在第一个循环中输入文本?
我想要做的是要求用户输入一些字符串来读入数组,然后要求用户输入该数量的字符串并将它们读入数组。当我运行这段代码时,它从不要求我在第一个 for 循环的第一个循环中输入内容,只是打印出“String #0: String #1:”,然后我就可以输入文本了。这是为什么?我做错了什么?
import java.util.Scanner;
public class ovn9
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Number of inputs: ");
int lines= sc.nextInt();
String[] text=new String[lines];
for(int x=0; x<text.length; x++)
{
System.out.print("String #"+x+": ");
text[x] = sc.nextLine();
}
for(int y=0; y<text.length; y++)
System.out.println(text[y]);
}
}
What I want to do is ask the user for a number of strings to read into an array, and then ask the user to input that number of strings and read them into the array. When I run this code it never asks me for an input the first cycle of the first for-loop, just prints out "String #0: String #1: " and then I can input text. Why is that and what did I do wrong?
import java.util.Scanner;
public class ovn9
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Number of inputs: ");
int lines= sc.nextInt();
String[] text=new String[lines];
for(int x=0; x<text.length; x++)
{
System.out.print("String #"+x+": ");
text[x] = sc.nextLine();
}
for(int y=0; y<text.length; y++)
System.out.println(text[y]);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
缓冲。
nextInt()
不会消耗输入缓冲区中输入输入数量时放置的换行符。在 for 循环的第 0 次迭代中,缓冲区中已经有一行输入,nextLine()
可以立即完成,程序只会在第 1 次迭代中等待新的输入行。忽略换行符在输入中,您可以在进入 for 循环之前添加另一个nextLine()
调用。Buffering.
nextInt()
does not consume the newline in the input buffer that was put there when you entered the number of inputs. In the iteration 0 of the for loop, there's already a line of input in the buffer andnextLine()
can complete immediately and the program will wait for new input line only in iteration 1. To ignore the newline in the input, you can add just anothernextLine()
call before entering the for loop.也许您应该更改循环以使用“sc.next()”
它可以通过 Java API
String next() 进行解释:从此扫描仪查找并返回下一个完整标记。
String nextLine():使扫描器前进到当前行并返回跳过的输入。
Maybe you should change your loop to use 'sc.next()'
It can be explained by the Java API
String next(): Finds and returns the next complete token from this scanner.
String nextLine(): Advances this scanner past the current line and returns the input that was skipped.