Question

I've just started working with Java, and I've been trying to get the console input to work properly. Here's the code:

System.out.println("Write a word: ");
Scanner keyboard = new Scanner(System.in);
System.out.println("DEBUG 1");
str = keyboard.nextLine();
System.out.println("DEBUG 2");
System.out.println(str);

This should just take input once and the print the input, like this:

Write a word: 
DEBUG 1
Hello            //My input
DEBUG 2
Hello            //Output

But this is what happens:

Write a word: 
Hello            //My input
DEBUG 1
                 //Waiting for new input
DEBUG 2
Hello            //The first input

So, it seems to me that it's somehow takes the input at the line Scanner keyboard = new Scanner(System.in); and then put it in my variable str. I use gcj to compile with the following commands to compile and run:

javac hello_world.java
java hello_world

EDIT: I've tried running the program on another computer now, using Ubuntu 10.04 64-bit, instead of Ubuntu 10.04 32-bit as before. I ran it the same way and did not recompile, and the program works fine.

Any ideas why it's behaving like this?

Was it helpful?

Solution

There could be a flushing/buffering issue that causes DEBUG 1 to be output later than you expect. I.e., println("DEBUG 1") could be executed before keyboard.nextLine(), but for some reason the output gets held up on the way, and not output until your input is read.

But I take it that you mean that you actually have to enter two newlines, one after Hello and one at the “Waiting for new input” line. If so, this is more difficult to explain. Perhaps a line termination incompatability issue.

Compiling and executing using the standard JDK gives the behavior you expect.

OTHER TIPS

I checked your program in eclipse running on windows using Oracle JDK 6, I got the expected result.

public static void main(String[] args) {
        System.out.println("Write a word: ");
        Scanner keyboard = new Scanner(System.in);
        System.out.println("DEBUG 1");
        String str = keyboard.nextLine();
        System.out.println("DEBUG 2");
        System.out.println(str);
    }

Result :

Write a word: 
DEBUG 1
hello
DEBUG 2
hello

OpenJDK is much similar to Oracle JDk and it is available for many distros from their package manager. Can you check with openJDK instead of gcj.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top