简体   繁体   English

Java扫描器nextInt()要求输入两次

[英]Java Scanner nextInt() asking for input twice

I've written the following simple program to read an integer from the console: 我编写了以下简单程序以从控制台读取整数:

import java.util.Scanner;

public class InputCheck {

    public static void main(String[] args) {
        int n;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter value of n:");
        n = in.nextInt();

        System.out.println("Value of n is: " + n);
    }
}

But I have to enter two inputs for the scanner to read it, even though only the first input is considered. 但是,即使仅考虑第一个输入,我也必须输入两个输入以供扫描仪读取它。 This is the output in the console: 这是控制台中的输出:

Enter value of n:
5
1
Value of n is: 5

I've seen a lot of similar questions, but none of them addressed this particular problem. 我见过很多类似的问题,但是没有一个解决这个特定的问题。

I know I can do nextLine() and then do a parseInt but I really want to know what I'm doing wrong here. 我知道我可以执行nextLine()然后执行parseInt,但是我真的很想知道我在这里做错了什么。

Thanks in advance. 提前致谢。

Edit: A lot of questions being asked about the code. 编辑:有关该代码的很多问题。 That is the exact code. 那是确切的代码。 Also I can confirm that I have observed the same behavior on Eclipse Juno and Kepler. 另外,我可以确认我在Eclipse Juno和Kepler上观察到了相同的行为。 Check here: i44.tinypic.com/2h83e52.png 在这里查看:i44.tinypic.com/2h83e52.png

Also compile and ran the program outside of Eclipse and still observing the same behavior. 还可以在Eclipse之外编译并运行该程序,并且仍然观察到相同的行为。 I'm using Java version 1.6.0. 我正在使用Java版本1.6.0。 Could this be related to that? 可能与此有关吗?

可能是您正在Eclipse中运行其他文件而不是此文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM