繁体   English   中英

Scanner.next()和Scanner.nextLine()

[英]Scanner.next() and Scanner.nextLine()

我有以下代码:

Scanner in = new Scanner (System.in);
String[] data = new String[5];

System.out.println("Please, enter the name of the customer ordering:");
data[0] = in.next();
System.out.print("Please, enter the assembly details: ");
data[1] = in.nextLine();
System.out.print("Please, enter the assembly id:");
data[2] = in.next();
System.out.println("Please, enter the date the assembly was ordered (MM-DD-YYYY):");
data[3] = in.next();

我试图让nextLine()读取多个单词,但在测试它的那一刻,它只是跳转到下一个扫描数据[2]。 我需要帮助。 我不知道该怎么做。

这应该工作:

    Scanner in = new Scanner (System.in);
    String[] data = new String[5];

    System.out.println("Please, enter the name of the customer ordering:");
    data[0] = in.nextLine();
    System.out.println("Please, enter the assembly details: ");
    data[1] = in.nextLine();
    System.out.println("Please, enter the assembly id:");
    data[2] = in.nextLine();
    System.out.println("Please, enter the date the assembly was ordered (MM-DD-YYYY):");
    data[3] = in.nextLine();
    in.close();

您应该使用nextLine()而不是next()来从控制台读取每一行

next() - 查找并返回此扫描器中的下一个完整标记nextLine() - 使此扫描器超过当前行并返回跳过的输入。

来自java API文档。

如果您不知道自己在做什么,请不要同时使用next()nextLine() ,这很容易导致错误。 next()读取下一个输入标记, nextLine()所有标记直到下一行。 所以如果你有这样的输入:

约翰\\ nSquirrels

(\\ n是换行符)

第一个next()返回“John”并离开我们

\\ nSquirrels

在此之后, nextLine()结束之前没有任何标记,因此您获得一个空字符串而不是“Squirrels”。

暂无
暂无

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

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