Java 扫描仪在使用next()或nextFoo()后跳过nextLine()?
我正在使用Java 扫描仪在使用next()或nextFoo()后跳过nextLine()?,java,io,java.util.scanner,Java,Io,Java.util.scanner,我正在使用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(); // R
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)
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.nextLine()
,执行第二个input.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)
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()
和string2=input.nextLine()
都会按照我的要求执行。问题在于input.nextLine()方法-它只读取int值。因此,当您继续使用input.nextLine()读取时,您将收到“\n”Enter键。因此,要跳过此操作,必须添加输入.nextLine()。希望这一点现在已经清楚了
试着这样做:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
这是因为当您输入一个数字,然后按enter键时,
input.nextInt()
只使用该数字,而不使用“行尾”。当执行input.nextLine()
时,它会使用第一次输入时仍在缓冲区中的“行尾”
相反,在input.nextLine()
之后立即使用input.nextLine()
,这是因为该方法不会读取通过点击“Enter”创建的输入中的换行符,因此对的调用在读取该换行符后返回
使用Scanner.nextLine
after或任何Scanner.nextFoo
方法(除了nextLine
本身)时,您会遇到类似的行为
解决方法:
- 在每个
之后放置一个Scanner.nextLine
调用或Scanner.nextLine
以使用该行的其余部分,包括换行符Scanner.nextFoo
- 或者,更好的方法是通过Scanner.nextLine读取输入,并将输入转换为所需的正确格式。例如,您可以使用方法转换为整数
- 之所以这样做是因为
input.nextInt()代码>不捕获换行符。通过添加input.nextLine(),您可以像其他建议的那样做代码>下方。
或者,您可以采用C#风格,将下一行解析为整数,如下所示:
int number = Integer.parseInt(input.nextLine());
这样做同样有效,而且可以为您节省一行代码。java.util.Scanner
似乎有很多关于这个问题的问题。我认为更具可读性/惯用的解决方案是调用scanner.skip([\r\n]+”)
在调用nextInt()
后删除任何换行符
编辑:正如@PatrickParker在下面提到的,如果用户在数字后面输入任何空格,这将导致无限循环。查看他们的答案,以获得更好的模式来使用skip:而不是input.nextLine()
使用input.next()
,这应该可以解决问题
修改代码:
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Insert a number: ");
int number = input.nextInt();
System.out.print("Text1: ");
String text1 = input.next();
System.out.print("Text2: ");
String text2 = input.next();
}
为什么每次阅读都不使用新的扫描仪呢?如下图所示。使用这种方法,您将不会面对您的问题
int i = new Scanner(System.in).nextInt();
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
input.nextLine();
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)
TL;DR
在每次调用scanner.newLine()
之前使用scanner.skip(\\R”)
(因为skip
使用正则表达式,其中\R
表示行分隔符),该调用在以下时间之后执行:
scanner.next()
scanner.next*键入*()
方法,如scanner.nextInt()
或更安全的变体:扫描器。在每个扫描器之前跳过(\\R?”)
。如果您不确定它是否会在扫描器之后被调用,则在扫描器之前跳过(
)
?
将使行分隔符序列成为可选的(这将防止跳过
方法(a)等待匹配序列-在系统等数据源仍然打开的情况下。在
(b)在文件或字符串等数据源终止/结束的情况下抛出java.util.NoSuchElementException
)
你需要知道的事情:
- 表示几行的文本在行之间还包含不可打印的字符(我们称之为行分隔符),如
- 回车符(CR-表示为
“\r”
)的字符串文字)
- 换行符(LF-in字符串文字表示为
“\n”
)
- 当您从控制台读取数据时,它允许用户键入他的响应,当他完成时,他需要以某种方式确认这一事实。为此,用户需要按键盘上的“回车”/“回车”键
重要的是,除了确保将用户数据放置到标准输入(由系统表示。
中由扫描仪读取)之外,此键还将在其后发送依赖于操作系统的行分隔符(如Windows\r\n
)
因此,当您向用户询问年龄等值时,用户键入42并按enter键,标准输入将包含“42\r\n”
问题
Scanner#nextInt
(以及其他Scanner#nextType
方法)不允许Scanner使用这些行分隔符。它将从系统中读取它们。在
中(否则扫描器将如何知道用户没有更多代表年龄
值的数字,而不是面对空白?),这将从标准输入中删除它们,但它还将在内部缓存这些行分隔符。我们需要记住的是,所有的Scanner方法总是从缓存的文本开始扫描
现在,Scanner#nextLine()
只需收集并返回所有字符,直到找到行分隔符(或流结束)。但由于从控制台读取数字后,会立即在扫描仪的缓存中找到行分隔符,因此它返回空字符串,这意味着扫描仪无法在这些行分隔符(或字符结尾)之前找到任何字符
class ScanReader {
/**
* @author Nikunj Khokhar
*/
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) return -1;
}
return buf[index++];
}
public char scanChar(){
int c=scan();
while (isWhiteSpace(c))c=scan();
return (char)c;
}
public int scanInt() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public String scanString() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() throws IOException {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public void scanLong(long[] A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanLong();
}
public void scanInt(int[] A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}
public double scanDouble() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
double res = 0;
while (!isWhiteSpace(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
res *= 10;
res += c - '0';
c = scan();
}
if (c == '.') {
c = scan();
double m = 1;
while (!isWhiteSpace(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
m /= 10;
res += (c - '0') * m;
c = scan();
}
}
return res * sgn;
}
}
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
class Main{
public static void main(String... as) throws IOException{
ScanReader sc = new ScanReader(System.in);
int a=sc.scanInt();
System.out.println(a);
}
}
class ScanReader....
Scanner stringScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
intScanner.nextInt();
String s = stringScanner.nextLine(); // unaffected by previous nextInt()
System.out.println(s);
intScanner.close();
stringScanner.close();
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
int firstNumber = input.nextInt();
int secondNumber = input.nextInt();
Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
public static Function<Scanner,String> scanLine = (scan -> {
String s = scan.nextLine();
return( s.length() == 0 ? scan.nextLine() : s );
});
System.out.println("Enter numerical value");
int option = input.nextInt(); // read numerical value from input
System.out.println("Enter 1st string");
String string1 = scanLine.apply( input ); // read 1st string
System.out.println("Enter 2nd string");
String string2 = scanLine.apply( input ); // read 2nd string
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
input.nextLine();
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)
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
package com.company;
import java.util.Scanner;
public class hackerrank {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
scan.nextLine(); // This line shall stop the skipping the nextLine()
String s = scan.nextLine();
scan.close();
// Write your code here.
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}