首页 > 解决方案 > 每次我在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 循环的每个代码中,都会出现此错误

标签: java

解决方案


不要使用多个扫描仪从同一输入读取。

如果您需要再次读取相同的输入,请不要关闭扫描仪,因为这会关闭输入流并且无法重新打开。

// 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.
}

推荐阅读