- 在调用了nextInt()后,我们可以先调用一次nextLine(),将该行剩下的内容抛弃;
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
- 全部都使用nextLine()读入,然后将其读入的数据转换为Integer。
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
本文介绍了一种在Java中处理输入的有效方法,特别是如何在使用nextInt()之后清除缓冲区中的换行符,确保程序正常运行。此外,还提供了一个通过nextLine()读取整数的方法,并附带了错误处理。
647

被折叠的 条评论
为什么被折叠?



