简体   繁体   中英

How can I handle new line character using java-util-scanner in this situation?

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

Something like this:

Scanner input = new Scanner(System.in);
while(!input.next().isEmpty()) { // only when you enter literal string 
//do your scanner stuff here
}

Try

Scanner input = new Scanner(System.in);
String name = "";
while(name.trim().isEmpty()) {
    name = input.next();
}

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