java 用Java打印用户输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14624592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:52:23  来源:igfitidea点击:

Printing user input in Java?

javaprintln

提问by Adz

Say I had the Scanner method, and I want to print the user input after that.

假设我有 Scanner 方法,然后我想打印用户输入。

Take this code for instance:

以这段代码为例:

    String randomWords;
    Scanner kb = new Scanner(System.in);

    System.out.print("Please enter two words separated: ");

    randomWords = kb.next();    
    System.out.println(randomWords);

And if the two separated words entered were

如果输入的两个分开的词是

hello world

Only

仅有的

hello 

is printed

被打印

Why is this? and how can I print both of the words with the space included?

为什么是这样?以及如何打印包含空格的两个单词?

Thank you.

谢谢你。

回答by PermGenError

Use Scanner#nextLine() instead,

使用Scanner#nextLine() 代替,

This method returns the rest of the current line, excluding any line separator at the end.

此方法返回当前行的其余部分,不包括末尾的任何行分隔符。

randomWords = kb.nextLine();    

Scanner#next()reads the next complete token basing on the delimiter.

Scanner#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

从此扫描器中查找并返回下一个完整的令牌。一个完整的标记前后是与分隔符模式匹配的输入

As default delimiter of the scanner is whitespace, you should explicitly define the delimiter for your scanner using Scanner#useDelimiter(str). If you use \nnext line as delimiter your curretn code would work.

由于扫描仪的默认分隔符是whitespace,您应该使用Scanner#useDelimiter(str)为您的扫描仪明确定义分隔符。如果您使用\n下一行作为分隔符,您当前的代码将起作用。

 Scanner kb = new Scanner(System.in).useDelimiter("\n");
    System.out.print("Please enter two words separated: "); 
    randomWords = kb.next();    
    System.out.println(randomWords);

回答by Avinash Nair

public static void main(String[] args) {
        String randomWords;
        Scanner kb = new Scanner(System.in);

        System.out.print("Please enter two words separated: ");

        randomWords = kb.nextLine(); 
        System.out.println(randomWords);
    }

回答by Anthony Accioly

Use Scanner.nextLine()method to read up to the line break (noninclusive).

使用Scanner.nextLine()方法读取到换行符(非包含)。

randomWords = kb.nextLine();