0

My problem is related to grabbing multiple user input strings using Scanner on System.in to retrieve a username/password tuple and store the tuple in a String array.

similar inquiry: Reading multiple Scanner inputs

However, they don't use try/catch and their code seems to work.

When running my code, I get a java.util.NoSuchElementException pointing towards the line : login[1] = input.nextLine();

public void getPassword() throws Exception {
        /* Create a string array to hold username and password */
        String[] login = {"a", "b"};
        System.out.println("Username:\n");
        try (Scanner input = new Scanner(System.in)) {
            login[0] = input.nextLine();
        } catch (NoSuchElementException e) {
            e.printStackTrace();
        }
        System.out.println("Password:\n");
        try (Scanner input = new Scanner(System.in)) {
            login[1] = input.nextLine();
        } catch (NoSuchElementException e) {
            e.printStackTrace();
        }
        System.out.println("username: " + login[0] + "\npassword: " + login[1]);
    }

What could be the problem?

4
  • Don't create a Scanner every time you want to read input. Create it once. Commented Mar 5, 2017 at 1:40
  • Should I remove the second try and catch and just put all of it in one block? Commented Mar 5, 2017 at 1:41
  • 1
    also, use hasNextLine(). that should prevent your exception but the way you're using the scanners is not the proper way. Commented Mar 5, 2017 at 1:41
  • I read many things about not using multiple wrappers for input stream. However, I'm new to java and my tutorial always uses this weird try/catch thing when opening a new scanner object. Would it be better to put everything into one block? Commented Mar 5, 2017 at 1:44

1 Answer 1

0

You don't need to catch NoSuchElementException if you first use one of the has*() methods.

For example, the following code will echo the two inputs to the console.

Scanner scan = new Scanner(System.in);
if (scan.hasNextLine()) {
    System.out.println(scan.nextLine());
}
if (scan.hasNextLine()) {
    System.out.println(scan.nextLine());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This did it for me. I removed the try/catch block and the "throws Exception" and replaced with similar lines above. I did not understand the use of the hasNextLine() method but I looked up documentation and now it is clear. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.