繁体   English   中英

为什么这段代码会执行两条 println 语句,而不是一条一条打印?

[英]Why does this piece of code execute two println statement instead of printing one by one?

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

此处详细介绍了更完整的答案,但为了概述, nextInt()仅使用您在控制台中提供的 integer ,但保留换行符\n原样。 nextLine()nextInt()之后被调用时,它会消耗这个\n字符并继续前进(基本上是读取空字符串)。 可以通过多种方式纠正此行为。

一种方法是使用nextLine()而不是nextInt()然后使用以下代码转换为int String s = sc.nextLine();

int id = Integer.valueOf(s);

或者,您可以在sc.nextLine()之后添加一个额外的 sc.nextLine sc.nextInt()以使用换行符,然后继续执行您的代码。 一个有趣的事实是,如果您对sc.nextInt()进行多次调用,那么您只需要在最后进行一次sc.nextLine()调用即可使用最后一个换行符。 系统输入已经跳过了所有先前的换行符!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM