Scanner scan = new Scanner(System.in);
String in;
int count = scan.nextInt();
for (int i = 0; i < count; i++){
System.out.print("Input "+i+" of "+count+": ");
in = scan.nextLine();
}
正如标题所述,此for循环在停止等待用户输入之前将其打印两次(“ i”变量增加一次)。我不明白为什么要这么做。我尝试使用while循环,结果相似。帮助吗?
答案 0 :(得分:1)
您应在scan.nextLine();
之后添加scan.Int();
。
Scanner scan = new Scanner(System.in);
String in;
int count = scan.nextInt();
scan.nextLine();
答案 1 :(得分:0)
尝试一下:
Scanner scan = new Scanner(System.in);
String in;
int count = Integer.parseInt(scan.next());
for (int i = 0; i < count; i++){
System.out.print("Input "+i+" of "+count+": ");
in = scan.nextLine();
}
请记住,您需要处理NaN异常
由@Stultuske在评论中建议的替代方法,是在scan.nextLine();
之后添加scan.next();
或scan.nextInt();