java - 每次我在java中使用带有扫描仪的循环时都会出现这个错误
问题描述
这是错误
import java.util.*;
public class CWH_Exercise2 {
public static void main(String[] args) {
for(int i = 0;i<=5;i++){
// Objects
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
// Code
System.out.println("Welcome!");
System.out.print("Your input: ");
String userMove = sc1.next();
if (userMove.equalsIgnoreCase("Yep")) {
System.out.println("Here it is again!");
}
else if (userMove.equalsIgnoreCase("Nope")){
System.out.println("Why I will print it again?");
}
else{
System.out.println("Try Again");
}
// Closes
sc1.close();
sc2.close();
}
}
}
在我使用 for-loop、do-while 循环或 while 循环的每个代码中,都会出现此错误
解决方案
不要使用多个扫描仪从同一输入读取。
如果您需要再次读取相同的输入,请不要关闭扫描仪,因为这会关闭输入流并且无法重新打开。
// Declare 1 scanner outside the loop.
Scanner sc1 = new Scanner(System.in);
// Remove sc2
// Loop to do stuff.
// Don't close sc1 at all: closing sc1 closes System.in;
// you didn't open System.in, so you shouldn't close it either.
for(int i = 0;i<=5;i++){
// Stuff.
}
推荐阅读
- dart - dart 2.1 中的 Mixins - “on”关键字
- c++ - 开发 C++ sdl 库 setpixel 或 putpixel 示例代码请求
- java - 为什么Androidx.appcompat.AppCompatActivity会抛出java.lang.NoSuchMethodError: No virtual method getMainExecutor()?
- asp.net-core-mvc - 在 ASP.NET CORE 中使用 AJAX 在 DateTimePicker 中显示数据库中的用户生日
- javascript - 使用 onClick 按钮创建卡片元素的克隆
- node.js - puppeteer 如何获取元素 tagName
- wso2 - 如何在 2 个窗口上进行计算/比较?
- javascript - Reactjs 渲染两次
- java - 获取列表的值
- api - 在 .net core API 的 httpresponse 内容中发送 json 数据