java - 为什么在我第二次输入内容之前循环中断
问题描述
当我没有发送任何输入时,我想打破循环。但是,当我在第二次输入要输入的nameS
内容时,尽管输入不是空的,但循环会自行中断。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("Name: ");
String nameS = sc.nextLine();
if(nameS.isEmpty()) {
break;
}
System.out.print("Student number: ");
int numberS = sc.nextInt();
}
}
解决方案
nextInt()
或next()
方法不读回车。通常在数字之后,您必须按上述方法未准备好的回车键。避免这种情况的排序方法是保留 1 个额外的sc.nextLine()
方法调用。它将读取并丢弃输入。
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Name: ");
String nameS = sc.nextLine();
if (nameS.isEmpty()) {
break;
}
System.out.print("Student number: ");
int numberS = sc.nextInt();
sc.nextLine();//you need to add this line in your code
System.out.println(numberS);
}
推荐阅读
- manim - manim 中 TracedPath 的问题
- sql - 如何在更新中执行连接查询?
- azure-devops - 如何为多个构建工件创建单个 yaml 发布管道
- c++ - qt多项目中的预编译头文件
- c++ - 在引用不同类中的变量时使用 !(not) 运算符
- php - 如何使用 PDO 更新具有正确数据类型的 json 列?
- javascript - 为什么我们无法获取跨域 iframe 的内容?
- kubernetes - 从没有 exec 的容器中获取正在运行的进程
- python - 具有未知参数的函数作为另一个函数/ Python的参数
- java - ImapMailReceiver 因提供的 taskScheduler 线程被阻塞而停止