【问题标题】:Scanner doesn't work in multiple methods?扫描仪不能以多种方式工作?
【发布时间】:2018-05-03 19:28:12
【问题描述】:

我在构造函数和另一个方法中使用了 Scanner 类,错误表明 Scanner 已关闭,但我在每个类中创建了两个不同的扫描仪对象。我意识到在方法执行完成后局部变量将被删除(即使在构造函数完成之前调用了execute)但是我认为在每个方法中创建一个对象应该注意这一点?

UserInterface() {
    System.out.println("Welcome! Which store would you like to look at?");
    Scanner scobj=new Scanner(System.in);
    storechoice=scobj.nextInt();
    printmenu();
    execute();
    //scobj.close();    
} 

public void execute() {
    Scanner scobj=new Scanner(System.in);
    String option1;
    int weekchoice;
    
    option1=scobj.nextLine();
    scobj.close();  
    
    switch(option1) {
        case "a":
            System.out.println("Which week?(0-4)");
            weekchoice=scobj.nextInt();
            f1.getStores(storechoice).totalsalesforweek(weekchoice);
            break;
            
        default:
            System.out.println("I'm sorry you must choose a-g or q to quit");
            break;
                
    }
}

我收到这些错误

IllegalStateException:` 扫描仪已关闭

ensureOpen(未知来源)

下一个(未知来源)

nextInt(未知来源)

nextInt(未知来源)

【问题讨论】:

  • 对所有内容使用相同的扫描仪,无需为相同的输入使用多个扫描仪

标签: java methods java.util.scanner


【解决方案1】:

在“execute()”方法中,关闭扫描仪

scobj.close();

然后,你会这样做:

weekchoice=scobj.nextInt();

其中一个扫描仪已关闭,在其上调用“nextInt()”会使您的程序崩溃。

把“scobj.close();”在您的方法的结束,或您使用它的任何地方。

它最终会看起来像:

public void execute() 
    {
        Scanner scobj=new Scanner(System.in);
        String option1;
        int weekchoice;

        option1=scobj.nextLine();


        switch(option1)
        {
        case "a":
            System.out.println("Which week?(0-4)");
            weekchoice=scobj.nextInt();
            f1.getStores(storechoice).totalsalesforweek(weekchoice);
            break;

        default:
            System.out.println("I'm sorry you must choose a-g or q to quit");
            break;

        }
        scobj.close(); 
    }

【讨论】:

【解决方案2】:

一旦Scanner 关闭,其内部输入流System.in 也将关闭。

因此,调用close() 方法后,您将无法再访问它。

来自 javadoc:

当 Scanner 关闭时,如果源实现了 Closeable 接口,它将关闭其输入源。

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

我建议您仅在 main() 方法的末尾调用 scObj.close()。那你就不用再担心其他方法的这个错误了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    相关资源
    最近更新 更多