0

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();
        }
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41
  • Does this answer your question? [java.util.NoSuchElementException - Scanner reading user input](https://stackoverflow.com/questions/13042008/java-util-nosuchelementexception-scanner-reading-user-input) – Ivar May 22 '21 at 16:22
  • 2
    Do not close `input`. That also closes `System.in`. – Elliott Frisch May 22 '21 at 16:25
  • 2
    If you close a Scanner this automatically closes the underlying Stream. If you close System.in, it can't be reopened. Solution: do not close a Scanner based on System.in until the program exits. – NomadMaker May 22 '21 at 16:26
  • okay should I just use it after the last userInput?? – Stelios Kapsis May 22 '21 at 17:01

0 Answers0