如何解决为什么这段代码执行两条 println 语句而不是一条一条打印?
Scanner sc4 = new Scanner(System.in);
System.out.println("\nEnter the ID of the student you want to update!: ");
int id = sc4.nextInt();
System.out.println("Print1!");
String name = sc4.nextLine();
System.out.println("Print2!");
String address = sc4.nextLine();
System.out.println("Enter the updated contact Number of the student: ");
String contact = sc4.nextLine();
System.out.println("Enter the updated CourseID of the student: ");
int courseId = sc4.nextInt();
studentService.updateStudentById(id,name,address,contact,courseId);
break;
此代码打印一次“输入...的 ID”,在收到我的输入后,它同时打印 Print1 和 Print2。为什么会发生这种情况?
在每个打印语句之前使用扫描仪解决了这个问题,但我想要一个好的编程方法来解决这个问题。
解决方法
如果您想向缓冲区添加新值,请使用 java.util.Scanner#next()。
如果你故意使用 java.util.Scanner#nextLine() 来显示缓冲区中的数据,那么你必须在缓冲区中放入一些东西(一些字符串)。
https://www.tutorialspoint.com/java/util/scanner_nextline.htm
,更完整的答案是详细的 here,但为了提供概述,nextInt()
仅使用您在控制台中提供的整数,但保留换行符 \n
原样。当 nextLine()
在 nextInt()
之后被调用时,它会消耗这个 \n
字符并向前移动(基本上是读取空字符串)。
这种行为可以通过多种方式补救。
一种方法是使用 nextLine()
而不是 nextInt()
,然后使用以下代码强制转换为 int
String s = sc.nextLine();
int id = Integer.valueOf(s);
或者,您可以在 sc.nextLine()
之后添加额外的 sc.nextInt()
以使用换行符,然后继续您的代码。
一个有趣的事实是,如果您多次调用 sc.nextInt()
,那么您只需要在末尾发出一次 sc.nextLine()
调用来消耗最后一个换行符。之前的所有换行都已经被系统输入跳过了!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。