简体   繁体   English

Java-摆脱空终止符

[英]Java - getting rid of null terminator

When do I need to scan in an extra line by using .nextLine() to pick up the \\n due to the enter key from the previous scan? 由于上次扫描的回车键,我何时需要使用.nextLine()来扫描\\n额外的一行? What i mean to ask is, after what kind of scan statements do i need to have an extra scan line to pick up the \\n . 我要问的是,在执行哪种类型的扫描语句后,我需要有一条额外的扫描线来拾取\\n .next() 。下一个() .nextDouble() .nextDouble() .nextInt? .nextInt? I tried looking online, but couldn't find an answer to this. 我尝试在网上查找,但找不到答案。

Whenever you use next() or any of the other Scanner methods that read a token , any white space that follows the token remains in the Scanner . 每当您使用next()或任何其他读取令牌的 Scanner方法时,该令牌后面的空白都将保留在Scanner That includes a newline character, if that happens to be the character that follows the token. 如果碰巧是令牌后面的字符,则包括换行符。 This is OK most of the time. 大多数时候都可以。

When you use nextLine() , what gets read is everything up to and including the next end-of-line. 当您使用nextLine() ,将读取直到下一行结束的所有内容。 This is OK if you want an entire line of text. 如果要整行文本,则可以。

The problem is when you mix these two strategies. 问题是当您混合使用这两种策略时。 If you have a line that contains a single token, and you read it with next() (or nextInt() , nextDouble() or any of the similar methods), then the following call to nextLine() will just read the end-of-line that follows the token, as opposed to the next line. 如果您的一行包含单个标记,并使用next() (或nextInt()nextDouble()或任何类似方法)进行读取,则对nextLine()的以下调用将仅读取nextLine()令牌后面的行,而不是下一行。 This is the one case when you need an extra nextLine() call. 当您需要额外的nextLine()调用时,就是这种情况。

For an example of the sort of program where you need this, see java string variable using .next() or .nextLine() where the OP has a call to nextInt() followed by a call to nextLine() without the "extra" nextLine() call. 有关需要该程序的示例,请参见使用.next()或.nextLine()的java字符串变量 ,其中OP调用了nextInt()随后调用了nextLine()而没有“多余” nextLine()调用。

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

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