首页 > 解决方案 > 扫描仪输入的 Java 问题并尝试 {/// } 最后 {input.close();}

问题描述

Java新手在这里...我想在按下按钮后扫描一些用户输入。我从键盘扫描的第一件事工作正常,但在第二个输入中程序崩溃。我相信问题出在第二次使用 try{//blocks of code}finally{input. close();} (虽然代码相同)。我使用它是为了摆脱扫描过程。我需要你的视线。感谢您的帮助。这是我的代码:

@Override
public void action Performed(Action Event e) {
    if(e.getSource()==button1){
        System.out.println("Sth");
        label1.setVisible(true);
        Scanner input = new Scanner(System.in);
        try {
            String userInput = "";
            System.out.println("Asking the user a q, (yes/no)");
            userInput = input.nextLine();
            if(userInput.equalsIgnoreCase("yes")) {
                System.out.println("Okay");
                int Temp = input.nextInt();
                System.out.println("Print the scanned value");
                input.close();
            }else if(userInput.equalsIgnoreCase("no")) {
                System.out.println("Default answer to q");
            }
        }finally{
            input.close();
        }
    } else if(e.getSource()==button2){
        System.out.println("Sth");
        label2.setVisible(true);
        Scanner input = new Scanner(System.in);
        try {
            String userInput = "";
            System.out.println("Q for user, (yes/no)");
            userInput = input.nextLine();
            if(userInput.equalsIgnoreCase("yes")) {
                System.out.println("Sth");
                int Time = input.nextInt();
                System.out.println("" + Time + "");
                input.close();
            }else if(userInput.equalsIgnoreCase("no")) {
                System.out.println("Okay");
            }
        }finally{
            input.close();
        }
    }
}

标签: javauser-interfacetry-finally

解决方案


推荐阅读