Scanner doesn't see after space

余生长醉 提交于 2019-11-26 04:53:16

问题


I am writing a program that asks for the person\'s full name and then takes that input and reverses it (i.e John Doe - Doe, John). I started by trying to just get the input, but it is only getting the first name.

Here is my code:

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

回答1:


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

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




回答2:


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.




回答3:


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.




回答4:


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




回答5:


try using this

String name = scanner.nextLine();



回答6:


 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



来源:https://stackoverflow.com/questions/19509647/scanner-doesnt-see-after-space

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