[英]Java print two lines together
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. 我连续打印4张照片,但它们之间有扫描方法。 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! 在此先感谢您的帮助!
println makes a new line while print does not. println换行,而print不换行。 You should consider either using println, flushing the buffer, or calling a new line escape character "\\n" 您应该考虑使用println,刷新缓冲区或调用换行符“ \\ n”
This is because the line above your switch
statement has key.nextInt()
* . 这是因为switch
语句上方的行具有key.nextInt()
* 。
The scanner reads the integer, but it leaves the end-of-line character '\\n'
in the buffer. 扫描程序读取整数,但是它将行尾字符'\\n'
留在缓冲区中。 You need to consume that '\\n'
character somehow, before the key.nextLine();
您需要以某种方式在key.nextLine();
之前使用该'\\n'
字符key.nextLine();
inside the switch statement returns some relevant data to you. 在switch语句中返回一些相关数据给您。
To fix this problem, insert 要解决此问题,请插入
key.nextLine();
in front of the switch
statement. 在switch
语句的前面。
* don't ask me how I know that :-) *不要问我我怎么知道:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.