Java print two lines together

為{幸葍}努か 提交于 2019-12-11 08:47:09

问题


I'm trying to print a message on the screen and after that, take a value from the keyboard. i have 4 prints in a row but i have scan methods between them. When i run my code, the first two prints run together and i can't insert a value at the first variable, after the first print.

case 1:
            System.out.println("###Book Data###");
            System.out.print("Name of the book:\t");
            String Name = key.nextLine();

            System.out.print("ISBN of the book:\t");
            String ISBN = key.nextLine();

            System.out.print("Author of the book:\t");
            String author = key.nextLine();

            System.out.print("Copies of the book:\t");
            int copies = key.nextInt();
            book Book = new book(ISBN,Name,author,copies);
            lib.AddBook(Book);
            break;


#########Text Printed######
Please enter your selection:    1
###Book Data###
Name of the book:       ISBN of the book:

Thanks in advance for your help!


回答1:


This is because the line above your switch statement has key.nextInt() *.

The scanner reads the integer, but it leaves the end-of-line character '\n' in the buffer. You need to consume that '\n' character somehow, before the key.nextLine(); inside the switch statement returns some relevant data to you.

To fix this problem, insert

key.nextLine();

in front of the switch statement.

* don't ask me how I know that :-)




回答2:


println makes a new line while print does not. You should consider either using println, flushing the buffer, or calling a new line escape character "\n"



来源:https://stackoverflow.com/questions/23301754/java-print-two-lines-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!