简体   繁体   中英

Why is my cursor on the wrong line after NextLine()?

public static void main(String[] args)
{ 
    String word; 
    System.out.println ("Please type hello");
    Scanner scanner = new Scanner(System.in); 
    word = scanner.nextLine();
    System.out.println ("Okay");    
}

I have a problem with nextLine() method and it is that when I type a word on a keyboard, I want the cursor of the keyboard to be on the next line of "Okay". However, it is on the same line as "Okay".

Can you please let me know how I can move the cursor to the next line it as I've been on this for 2 hours and couldn't find any solutions?

Thanks in advance.

I tried to find solutions for this problem but all of them are related to nextInt(), which I haven't used in this code. Also I tried to use "\n" but it didn't solve anything.

I suspect you are using the simulated console in your IDE (Eclipse or something) to test-run your program, right? Is this what happens?

Eclipse 控制台屏幕截图

The simple answer is: This doesn't work like a real terminal. While you can just type even if the cursor is in the "wrong" line and the input text will appear in the "correct" line, it doesn't create a perfect illusion of a proper terminal.

Export your program to a runnable .jar file and run it on your systems terminal/console with java -jar yourProgramName.jar and you will be happy!

Did you missed a System.out.println ?

public static void main(String[] args)
{ 
    String word; 
    System.out.println ("Please type hello");
    Scanner scanner = new Scanner(System.in); 
    word = scanner.nextLine();
    System.out.println (word); // << missed line
    System.out.println ("Okay");    
}

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