Reputation: 2881
I have a simple homework assignment, I'm making a simple UI (not GUI) and I'm using scanner for input.
I want to read 3 strings (Name, address, social security number)
If the user however does not insert anything simply presses enter, my code breaks. Instead of the 3 strings I need, I get more strings and they miss match.
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
name = input.nextLine();
}
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
address = input.nextLine();
}
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
ssnumb = input.nextLine();
}
So if user presses enter, creates a new line character, the input spills. How can I either avoid this or eliminate empty lines ?
Example:
enter
Nick
Mars
some number
I would have:
Name:
Address:
Nick
Social Security Number:
Mars
Upvotes: 0
Views: 10384
Reputation: 136012
Try
Scanner input = new Scanner(System.in);
String name = "";
while(name.trim().isEmpty()) {
name = input.next();
}
Upvotes: 1
Reputation: 46408
Something like this:
Scanner input = new Scanner(System.in);
while(!input.next().isEmpty()) { // only when you enter literal string
//do your scanner stuff here
}
Upvotes: 1