简体   繁体   中英

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.

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. Check here: i44.tinypic.com/2h83e52.png

Also compile and ran the program outside of Eclipse and still observing the same behavior. I'm using Java version 1.6.0. Could this be related to that?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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