1

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();
1
  • Get the complete line from input and trim the spaces. That's the best practise! Commented Dec 27, 2020 at 21:34

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.