Java problem with Scanner input and try {/// } finally {input.close();}

70 Views Asked by At

Java newbie here... I want to scan some user input after a button is pressed. The first thing that I scan from keyboard works fine but in the second input the programm crashes. I believe the problem is with the second use of try{//blocks of code}finally{input. close();} (same code though). I used it so I can get out of the scanning process. I need your sights. Thx for the help. Here is my code:

@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();
        }
    }
}
0

There are 0 best solutions below