1

I'm new to Java so this is a very basic question. I get and error when entering a name with spaces. What do I need to change please? steering me to info is great too.

how do I allow input with spaces.

import java.util.Scanner;

    public class yes {

        public static void main(String[] args) {
        Name = in.next();
        ....
      }
  }
John Joe
  • 12,412
  • 16
  • 70
  • 135
yoda
  • 121
  • 1
  • 9

3 Answers3

1

Please use in.nextLine();

import java.util.Scanner;

public class Yes {

    public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       String name = in.nextLine();
       ....
  }
}
GrabNewTech
  • 631
  • 6
  • 14
1

Here's what you need to change :

import java.util.Scanner;

public class Yes {

    public static void main(String[] args) {
    String name;
    Scanner in = new Scanner(System.in);
    name = in.nextLine();
    ....
  } 
}

Here's why : The next() method reads the input on current line till a space is detected. It advances to next line only when you press Enter/Return.

On the other hand, nextLine() method advances to the next line and returns the input on the current line.

You can read more about Scanner class here.

Also, it is good to follow Java naming conventions. Thanks!

John Joe
  • 12,412
  • 16
  • 70
  • 135
Yogesh
  • 699
  • 1
  • 6
  • 21
0

Use the Scanner.nextLine(); method.

import java.util.Scanner;

    public class yes {

        public static void main(String[] args) {
        String name = in.nextLine();
        ....
      }
  }

Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31