Java 扫描仪在for循环中,在获取任何输入之前循环一次 Scanner scan=新的扫描仪(System.in); 串入; int count=scan.nextInt(); for(int i=0;i

Java 扫描仪在for循环中,在获取任何输入之前循环一次 Scanner scan=新的扫描仪(System.in); 串入; int count=scan.nextInt(); for(int i=0;i,java,for-loop,Java,For Loop,正如标题所说,这个for循环在停止等待用户输入之前将行打印两次(“i”变量递增一次)。我不明白为什么会这样。我尝试使用while循环,得到了类似的结果。帮助?试试这个: Scanner scan = new Scanner(System.in); String in; int count = scan.nextInt(); for (int i = 0; i < count; i++){ System.out.print("Input "+i

正如标题所说,这个for循环在停止等待用户输入之前将行打印两次(“i”变量递增一次)。我不明白为什么会这样。我尝试使用while循环,得到了类似的结果。帮助?

试试这个:

    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();
    }
Scanner scan=新的扫描仪(System.in);
串入;
int count=Integer.parseInt(scan.next());
for(int i=0;i
请记住,您需要处理NaN异常



或者,正如@Stultuske在评论中建议的那样,添加
scan.nextLine()
扫描.next()
扫描.nextInt()之后

您应该添加
scan.nextLine()
scan.Int()之后

添加一个简单的扫描;或scan.nextLine();在扫描之后。nextInt();在循环之前。或者读取第一条语句中的字符串,并将其解析为int。
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();
}
Scanner scan = new Scanner(System.in);
String in;
int count = scan.nextInt();
scan.nextLine();