我有以下代码:
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。我需要帮助。我不知道该怎么办。
发布于 2013-11-25 18:36:51
这应该是可行的:
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()从控制台读取每一行
发布于 2013-11-25 18:26:11
nextLine() --查找并返回此扫描器中的下一个完整标记nextLine()--使此扫描器前进到当前行,并返回跳过的输入。
从java API文档中获取。
发布于 2013-11-25 18:43:17
如果你不知道自己在做什么,不要同时使用next()和nextLine(),这很容易导致错误。next()读取下一个输入标记,nextLine()所有标记直到下一行。所以如果你有这样的输入:
约翰\n松鼠
(\n是换行符)
第一个next()返回"John“并离开我们
\n松鼠
在此之后,松鼠在行尾之前将不面对任何标记,因此您将得到一个空字符串,而不是“nextLine()”。
https://stackoverflow.com/questions/20189486
复制相似问题