简体   繁体   中英

Grabbing multiple string inputs from System.in using Scanner

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM