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?
Scannerevery time you want to read input. Create it once.