首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scanner.next()和Scanner.nextLine()

Scanner.next()和Scanner.nextLine()
EN

Stack Overflow用户
提问于 2013-11-25 18:15:23
回答 3查看 196关注 0票数 0

我有以下代码:

代码语言:javascript
复制
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()读取多个单词,但在测试时,它只是跳到下一次扫描data2。我需要帮助。我不知道该怎么办。

EN

回答 3

Stack Overflow用户

发布于 2013-11-25 18:36:51

这应该是可行的:

代码语言:javascript
复制
    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()从控制台读取每一行

票数 2
EN

Stack Overflow用户

发布于 2013-11-25 18:26:11

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

从java API文档中获取。

票数 0
EN

Stack Overflow用户

发布于 2013-11-25 18:43:17

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

约翰\n松鼠

(\n是换行符)

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

\n松鼠

在此之后,松鼠在行尾之前将不面对任何标记,因此您将得到一个空字符串,而不是“nextLine()”。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20189486

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档