简体   繁体   English

用Java打印用户输入?

[英]Printing user input in Java?

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. 谢谢。

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) . 由于扫描仪的默认定界符为空白 ,因此应使用Scanner#useDelimiter(str)为扫描仪明确定义定界符。 If you use \\n next line as delimiter your curretn code would work. 如果将\\n下一行用作分隔符,则您的curretn代码将起作用。

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

使用Scanner.nextLine()方法读取换行符(不包括在内)。

randomWords = kb.nextLine();
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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM