Scanner doesn't see after space

纵饮孤独 提交于 2019-11-26 15:28:21
Prabhakaran

Change to String name = scanner.nextLine(); instead of String name = scanner.next();

See more on documentation here - next() and nextLine()

Try replacing your code

String name = scanner.nextLine();

instead

String name = scanner.next();

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

From Scanner documentation:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

and

public String next()

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

This means by default the delimiter pattern is "whitespace". This splits your text at the space. Use nextLine() to get the whole line.

scanner.next(); takes only the next word. scanner.nextLine(); should work. Hope this helps

try using this

String name = scanner.nextLine();
 public static void processName(Scanner scanner) {
        System.out.print("Please enter your full name: ");
        scanner.nextLine();
        String name = scanner.nextLine();
        System.out.print(name);
    }

Try the above code Scanner should be able to read space and move to the next reference of the String

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!