使用Next()或NextFoo()之后,Scanner跳过NextLine()?
我正在使用 scanner
方法 nextInt()
和 nextline()
用于阅读输入。
看起来这样:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
问题是,在输入数值后,跳过了第一个 input.nextline()
,第二个 input.nextline()被执行,所以我的输出看起来像这样:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
我测试了我的应用程序,看起来问题在于使用 input.nextint()
。如果我删除它,则两个 string1 = input.nextline()
and string2 = input.nextline()
按照我希望的方式执行。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(25)
那是因为
scanner.nextint
方法在您创建的输入中未读取 newline 字符,通过击中“ Enter”创建的输入,因此调用scanner.nextline < /code>
阅读该 newline 后返回。
当您使用
scanner.nextline
之后,您将遇到类似的行为/java/util/scanner.html#next()“ rel =“ noreferrer”>scanner.next()
或任何scanner.nexner.nextfoo
method(除外NextLine
本身)。解决方法:
要么将
scanner.nextline
在每个scanner.nextint
或scanner.nextfoo
之后呼叫消耗该行的其余部分,包括 newline :或更好的是,通过
scanner.nextline
读取输入,然后将您的输入转换为所需的正确格式。例如,您可以使用integer.parseint(string)
方法:That's because the
Scanner.nextInt
method does not read the newline character in your input created by hitting "Enter" and so the call toScanner.nextLine
returns after reading that newline.You will encounter the similar behaviour when you use
Scanner.nextLine
afterScanner.next()
or anyScanner.nextFoo
method (exceptnextLine
itself).Workaround:
Either put a
Scanner.nextLine
call after eachScanner.nextInt
orScanner.nextFoo
to consume the rest of that line including newline:Or, even better, read the input through
Scanner.nextLine
and convert your input to the proper format you need. For example, you may convert to an integer using theInteger.parseInt(String)
method:问题在于
input.nextint()
方法;它只读取int值。因此,当您继续使用input.nextline()
继续阅读时,您会收到“ \ n” Enter键。因此,要跳过此功能,您必须添加input.nextline()
。这样尝试,而是:
The problem is with the
input.nextInt()
method; it only reads the int value. So when you continue reading withinput.nextLine()
you receive the "\n" Enter key. So to skip this you have to add theinput.nextLine()
.Try it like this, instead:
这是因为当您输入一个数字时,请按 Enter ,
input.nextint()
仅消耗数字,而不是“行的结尾”。当input.nextline()
执行时,它会消耗第一个输入从缓冲区中仍在缓冲区中的“末端”。而是在
input> input.nextint()
之后立即使用input.nextline()
It's because when you enter a number then press Enter,
input.nextInt()
consumes only the number, not the "end of line". Wheninput.nextLine()
executes, it consumes the "end of line" still in the buffer from the first input.Instead, use
input.nextLine()
immediately afterinput.nextInt()
java.util.scanner
似乎有很多问题。我认为一个更可读/惯用的解决方案将是调用scanner.skip(“ [\ r \ n]+”)
在调用nextint()
之后删除任何newline字符 。编辑:正如@patrickparker下面指出的那样,如果用户输入数字之后的任何空格,这将导致无限循环。请参阅他们的答案,以获取与SKIP一起使用的更好模式: https://stackoverflow.com/a/a/42471816/143585
There seem to be many questions about this issue with
java.util.Scanner
. I think a more readable/idiomatic solution would be to callscanner.skip("[\r\n]+")
to drop any newline characters after callingnextInt()
.EDIT: as @PatrickParker noted below, this will cause an infinite loop if user inputs any whitespace after the number. See their answer for a better pattern to use with skip: https://stackoverflow.com/a/42471816/143585
tl; dr
nextline()
是(a)是(a)首先阅读指令,(b)先前的读取指令也是nextline()
。如果您不确定以上两个是正确的,则可以使用
scanner.skip(“ \\ r?”)
在调用scanner.nextline()
之前代码> next()nextint()
将留下潜在的行分隔符 - 由 return return 键创建,这将影响nextline()。
.skip(“ \\ r?”)
会让我们消耗此不必要的行分隔符。skip
使用REGEX其中\ r
表示行分隔符?
将制造\ r
可选 - 哪个将阻止跳过
从:system.in
,插座的输入流等等。java.util.nosuchelementException
在您需要知道的内容时:
文本代表很少的行还包含行之间的不可打印字符(我们称它们为行分隔符)
carriagare返回(cr-在字符串文字中表示为
“ \ r”
)line feed(lf-在字符串文字中表示为
“ \ n”
)当您从控制台读取数据时,它允许用户键入他的响应,完成后,他需要以某种方式确认这一事实。为此,要求用户按键盘上的“ Enter”/“ return”键。
重要的是,该密钥在确保将用户数据放置到标准输入(由
System.in
表示)也发送OS依赖行分隔符(例如Windows\ r \ n
)。因此,当您向用户询问
age
的值时,用户类型42并按ENTER,标准输入将包含“ 42 \ r \ n”
。问题
扫描仪#nextint
(和其他scanner#next type
方法)不允许扫描仪到消耗这些线分隔符。它将从system.in
读取它们(否则扫描仪如何知道,用户不再有代表age
值的数字,而不是面对whitespace?)哪个会删除它们从标准输入中,但也将 CACHE 内部分离器。我们需要记住的是,所有扫描仪方法总是从缓存的文本开始扫描。现在
扫描仪#nextline()
只需收集并返回所有字符,直到它找到行分隔符(或流的结尾)。但是,由于在读取控制台的数字后立即在扫描仪的高速缓存中找到了线分离器,因此它返回空字符串,这意味着扫描仪无法在这些行分隔符(或流的结尾)之前找到任何字符。btw
nextline
也消耗那些行分隔符。解决方案
因此,当您要索要数字,然后在整个行中索要数字时,同时避免了
NextLine
的结果,要么NextInt
将行分隔机从扫描仪缓存中消耗。nextline
,skip(“ \\ r”)
>或skip(“ \ r \ n | \ r | \ n”)
让Scanner Skip skip part由行分隔符匹配(更多有关\ r
: https://stackoverflow.com/a/31060125 )next> nextint
(nornext> next
,next ,或任何nextType
方法)。而是使用NextLine
逐行阅读整个数据,并从每行分析数字(假设一行仅包含一个数字)到适当的类型,例如int
viainteger .parseint
。btw :
scanner#next type
方法可以 skip deleimiters(默认情况下,所有空间像标签一样,行分隔符),包括扫描仪缓存的符号,直到他们找到下一个非核子值(令牌)为止。感谢此输入,例如“ 42 \ r \ n \ r \ r \ n321 \ r \ r \ n \ r \ r \ n \ n \ r \ nfoobar”
代码将能够正确分配
num1 = 42 = 42 < /code>
num2 = 321
name = foobar
。TL;DR
nextLine()
is safe to call when (a) it is first reading instruction, (b) previous reading instruction was alsonextLine()
.If you are not sure that either of above is true you can use
scanner.skip("\\R?")
before callingscanner.nextLine()
since calls likenext()
nextInt()
will leave potential line separator - created by return key which will affect result ofnextLine()
. The.skip("\\R?")
will let us consume this unnecessary line separator.skip
uses regex where\R
represents line separators?
will make\R
optional - which will preventskip
method from:System.in
, input stream from socket, etc.java.util.NoSuchElementException
in case ofThings you need to know:
text which represents few lines also contains non-printable characters between lines (we call them line separators) like
carriage return (CR - in String literals represented as
"\r"
)line feed (LF - in String literals represented as
"\n"
)when you are reading data from the console, it allows the user to type his response and when he is done he needs to somehow confirm that fact. To do so, the user is required to press "enter"/"return" key on the keyboard.
What is important is that this key beside ensuring placing user data to standard input (represented by
System.in
which is read byScanner
) also sends OS dependant line separators (like for Windows\r\n
) after it.So when you are asking the user for value like
age
, and user types 42 and presses enter, standard input will contain"42\r\n"
.Problem
Scanner#nextInt
(and otherScanner#nextType
methods) doesn't allow Scanner to consume these line separators. It will read them fromSystem.in
(how else Scanner would know that there are no more digits from the user which representage
value than facing whitespace?) which will remove them from standard input, but it will also cache those line separators internally. What we need to remember, is that all of the Scanner methods are always scanning starting from the cached text.Now
Scanner#nextLine()
simply collects and returns all characters until it finds line separators (or end of stream). But since line separators after reading the number from the console are found immediately in Scanner's cache, it returns empty String, meaning that Scanner was not able to find any character before those line separators (or end of stream).BTW
nextLine
also consumes those line separators.Solution
So when you want to ask for number and then for entire line while avoiding that empty string as result of
nextLine
, eithernextInt
from Scanners cache bynextLine
,skip("\\R")
orskip("\r\n|\r|\n")
to let Scanner skip part matched by line separator (more info about\R
: https://stackoverflow.com/a/31060125)nextInt
(nornext
, or anynextTYPE
methods) at all. Instead read entire data line-by-line usingnextLine
and parse numbers from each line (assuming one line contains only one number) to proper type likeint
viaInteger.parseInt
.BTW:
Scanner#nextType
methods can skip delimiters (by default all whitespaces like tabs, line separators) including those cached by scanner, until they will find next non-delimiter value (token). Thanks to that for input like"42\r\n\r\n321\r\n\r\n\r\nfoobar"
codewill be able to properly assign
num1=42
num2=321
name=foobar
.之所以这样做,是因为
input.nextint();
不会捕获新线。您可以像通过在下面添加input.nextline();
。另外,您可以做到C#样式,并将隔壁分析到这样的整数:
也这样做也可以为您节省一系列代码。
It does that because
input.nextInt();
doesn't capture the newline. you could do like the others proposed by adding aninput.nextLine();
underneath.Alternatively you can do it C# style and parse a nextLine to an integer like so:
Doing this works just as well, and it saves you a line of code.
代替
input.nextline()
使用input.next()
,应该解决问题。修改的代码:
Instead of
input.nextLine()
useinput.next()
, that should solve the problem.Modified code:
如果您想同时阅读字符串和INT,则解决方案是使用两个扫描仪:
If you want to read both strings and ints, a solution is to use two Scanners:
为了避免问题,请在
nextline();
之后使用 nextint(); 之后,因为它有助于清除缓冲区。当您按输入
nextInt();
不会捕获新行,因此请稍后跳过scanner
代码。In order to avoid the issue, use
nextLine();
immediately afternextInt();
as it helps in clearing out the buffer. When you pressENTER
thenextInt();
does not capture the new line and hence, skips theScanner
code later.如果您想快速扫描输入而不会混淆扫描仪类NextLine()方法,请使用自定义输入扫描仪。
代码:
优点:
:
用法:
scanReader sc = new ScanReader(System.in);
3。导入必要的类:
导入java.io.bufferedinputstream;
导入java.io.ioexception;
导入java.io.inputstream;
4。从您的主要方法中抛出ioException以处理异常
5。使用提供的方法。
6。享受
示例:
If you want to scan input fast without getting confused into Scanner class nextLine() method , Use Custom Input Scanner for it .
Code :
Advantages :
Methods :
Usage :
ScanReader sc = new ScanReader(System.in);
3. Import necessary Classes :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
4. Throw IOException from your main method to handle Exception
5. Use Provided Methods.
6. Enjoy
Example :
sc.nextline()
与解析输入相比更好。因为性能明智,这将是好的。
sc.nextLine()
is better as compared to parsing the input.Because performance wise it will be good.
我想我参加聚会很晚了
。您的代码不起作用的原因是,从输入(输入INT输入)中没有其他可存储在
String1
中。我将为整个主题提供更多的启示。考虑 nextline()作为扫描仪类中 nextfoo()方法中的奇数。让我们快速举个例子。假设我们有两行代码,如下:
如果我们输入以下值(作为单个输入行)
我们的
firstNumber
和secondnumber
变量的值分别为54和234。这样做的原因是因为新的线feed( ie \ n ) 不是 在NextInt()方法采用时会自动生成在值中。它只是采用“下一个int” 并继续前进。对于NextLine()除外的其余方法,其余的方法是相同的。nextline()在获得值后立即生成新的线供稿;这就是@RoHitjain的意思,说新的线供稿被“消耗”。
最后,Next()方法仅采用最近的字符串而无需生成新线路;这使得这是在同一单线内采用单独字符串的优先方法。
我希望这会有所帮助..快乐的编码!
I guess I'm pretty late to the party..
As previously stated, calling
input.nextLine()
after getting your int value will solve your problem. The reason why your code didn't work was because there was nothing else to store from your input (where you inputted the int) intostring1
. I'll just shed a little more light to the entire topic.Consider nextLine() as the odd one out among the nextFoo() methods in the Scanner class. Let's take a quick example.. Let's say we have two lines of code like the ones below:
If we input the value below (as a single line of input)
The value of our
firstNumber
andsecondNumber
variable become 54 and 234 respectively. The reason why this works this way is because a new line feed (i.e \n) IS NOT automatically generated when the nextInt() method takes in the values. It simply takes the "next int" and moves on. This is the same for the rest of the nextFoo() methods except nextLine().nextLine() generates a new line feed immediately after taking a value; this is what @RohitJain means by saying the new line feed is "consumed".
Lastly, the next() method simply takes the nearest String without generating a new line; this makes this the preferential method for taking separate Strings within the same single line.
I hope this helps.. Merry coding!
在我的一个用途酶中,我的场景是读取字符串值之前的几个整数值。我必须使用“ for / wher loop < / strong>”来读取值。在这种情况下,以上建议均无效。
使用
input.next()
而不是input.nextline()
修复了问题。希望这对处理类似情况的人可能会有所帮助。In one of my usecase, I had the scenario of reading a string value preceded by a couple of integer values. I had to use a "for / while loop" to read the values. And none of the above suggestions worked in this case.
Using
input.next()
instead ofinput.nextLine()
fixed the issue. Hope this might be helpful for those dealing with similar scenario.如果我期望非空输入
避免:
- &nbsp;如果未选中的
scan.nextline()
作为解决方案,则数据丢失如果以下输入- &nbsp;由于
scan.nextline()
仅由部分读取行引起的数据丢失被scan.next()
(输入:“ yippie&nbsp; ya&nbsp; yeah yeai )- &nbsp;
scanner
methods 的分析输入时抛出异常
s在使用if I expect a non-empty input
avoids:
– loss of data if the following input is eaten by an unchecked
scan.nextLine()
as workaround– loss of data due to only partially read lines because
scan.nextLine()
was replaced byscan.next()
(enter: "yippie ya yeah")–
Exception
s that are thrown when parsing input withScanner
methods (read first, parse afterwards)used in above example:
使用2个扫描仪对象而不是一个
Use 2 scanner objects instead of one
AS
nextxxx()
方法不读取newline
,nextline()
。我们可以使用scanner.skip()<读取任何
nornewline
newlinevalue
value(int
)< /代码>如下:As
nextXXX()
methods don't readnewline
, exceptnextLine()
. We can skip thenewline
after reading anynon-string
value (int
in this case) by usingscanner.skip()
as below:使用此代码将解决您的问题。
Use this code it will fix your problem.
要解决此问题,只需使 scan.nextline(),其中 scan 是扫描仪对象的一个实例。例如,我正在使用一个简单的hackerrank问题进行解释。
}
To resolve this problem just make a scan.nextLine(), where scan is an instance of the Scanner object. For example, I am using a simple HackerRank Problem for the explanation.
}
nextline()
将直接读取为空行,而无需等待文本。通过添加额外的扫描仪来消耗空线来简单解决方案:
The
nextLine()
will read enter directly as an empty line without waiting for the text.Simple solution by adding an extra scanner to consume the empty line:
对于Java的初学者编码器来说,这是一个非常基本的问题。当我开始使用Java时,我也遇到了同样的问题(自学教学)。
实际上,当我们获取整数数据类型的输入时,它仅读取整数值并留下newline(\ n)字符,并且当我们尝试采用新输入时,此行(即通过整数动态输入借鉴了新线路)会产生问题。
例如。就像我们获取整数输入一样,然后在尝试获取字符串输入之后。
Value2将自动读取Newline字符,并且不会获取用户输入。
解决方案:
只是我们需要添加一行代码,然后再进行下一个用户输入IE
或
注意:不要忘记关闭扫描仪以防止内存泄漏;
This is a very basic problem for beginner coders in java. The same problem I also have faced when I started java (Self Taught).
Actually, when we take an input of integer dataType, it reads only integer value and leaves the newLine(\n) character and this line(i.e. leaved new line by integer dynamic input )creates the problem when we try to take a new input.
eg. Like if we take the integer input and then after try to take an String input.
the value2 will auto read the newLine character and will not take the user input.
Solution:
just we need to add one line of code before taking the next user input i.e.
or
Note: don't forget to close the Scanner to prevent memory leak;
问题是input.nextint()方法 - 它仅读取int值。因此,当您继续使用input.nextline()继续阅读时,您会收到“ \ n”输入密钥。因此,要跳过此功能,您必须添加input.nextline()。希望这应该很清楚。
这样尝试:
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
使用BufferedReader类用于输入字符串,这不会创建问题
Use BufferedReader class to input string, this will not create problems
为什么不为每次阅读使用新的扫描仪?如下。通过这种方法,您不会面对您的问题。
Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.