简体   繁体   中英

Including spaces in Scanner in java

I am writing a simple code that takes number,name,surname from the user with scanner. But when user enters name with spaces in it(two or more names) the code thinks string after the first space is surname. I tried using input.nextLine(); in that case it skipped name completely and took only surname from the user.

Scanner input = new Scanner(System.in);
System.out.println("Enter number");
int num = input.nextInt();
System.out.println("Enter Name");
String name = input.next();
System.out.println("Enter Surname");
String surname = input.next();

Try this:

Scanner input = new Scanner(System.in);
System.out.println("Enter number");
int num=input.nextInt();
input.nextLine(); // add this
System.out.println("Enter Name");
String name=input.nextLine();
System.out.println("Enter Surname");
String surname=input.nextLine();
System.out.println(num + " - " + name + " - " + surname);

Sample input/output:

Enter number
1
Enter Name
user name
Enter Surname
sur name
1 - user name - sur name

Use sc.nextLine() instead of sc.next() to read String with spaces

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