-1

I'm new to Java and to coding in general, and I can't get a second scanner to work on my simple program. Having the second scanner in the program gives me the following error:

Exception in thread "main" How are you feeling? java.util.NoSuchElementException: No line found

Here is my code:

import java.util.Scanner;
public class Part2 {
public static void main(String[] args) {
    
    //This part asks the user how they are doing, and then it says hello to them
    Scanner userName = new Scanner(System.in);
    System.out.print("What is your name? ");
    String name = userName.nextLine();
    userName.close();
    System.out.println("Hello "+name);
    
    //This part asks the user how they are feeling, and then it says it is happy that they are feeling that way
    Scanner userAttitude = new Scanner(System.in);
    System.out.print("How are you feeling? ");
    String attitude = userAttitude.nextLine();
    userAttitude.close();
    System.out.println("Glad to hear you are feeling "+attitude);
    
    

}

}

1 Answers1

0

Don't close System.in

When you closed the Scanner, that is what it did.

Also, there was no need to create a second Scanner on the same input stream: use the first one.

Patrick Parker
  • 4,863
  • 4
  • 19
  • 51