ble*_*one 627 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(); // 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)
Run Code Online (Sandbox Code Playgroud)
问题是输入数值后,第一个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
Run Code Online (Sandbox Code Playgroud)
我测试了我的应用程序,看起来问题在于使用input.nextInt().如果我删除它,然后这两个string1 = input.nextLine()和string2 = input.nextLine()执行,我希望他们能.
Roh*_*ain 752
那是因为该Scanner.nextInt方法不会通过点击"Enter"来读取输入中创建的换行符,因此Scanner.nextLine在读取该换行符后返回调用.
当您使用Scanner.nextLineafter Scanner.next()或任何Scanner.nextFoo方法(nextLine自身除外)时,您将遇到类似的行为.
解决方法:
要么把一个Scanner.nextLine电话后,每Scanner.nextInt或Scanner.nextFoo消耗该行包括休息换行符
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
Run Code Online (Sandbox Code Playgroud)或者,更好的是,通过读取输入Scanner.nextLine并将输入转换为您需要的正确格式.例如,您可以使用Integer.parseInt(String)方法转换为整数.
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
Run Code Online (Sandbox Code Playgroud)Pri*_*ine 191
问题在于input.nextInt()方法 - 它只读取int值.因此,当您继续使用input.nextLine()读取时,您会收到"\n"Enter键.所以要跳过这个,你必须添加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();
Run Code Online (Sandbox Code Playgroud)
Boh*_*ian 73
这是因为当你输入一个数字然后按Enter,input.nextInt()只消耗数字,而不是"行尾".当input.nextLine()执行时,它会消耗来自第一输入缓冲器中的"行结束"静止.
相反,请input.nextLine()立即使用input.nextInt()
Den*_*kiy 42
关于这个问题似乎有很多问题java.util.Scanner.我认为更可读/惯用的解决方案是在调用scanner.skip("[\r\n]+")后调用删除任何换行符nextInt().
编辑:正如下面提到的@PatrickParker,如果用户在数字后输入任何空格,这将导致无限循环.有关与skip一起使用的更好模式,请参阅他们的答案:https://stackoverflow.com/a/42471816/143585
Ele*_*fee 30
这样做是因为input.nextInt();没有捕获换行符.你可以通过添加一个input.nextLine();底层来完成其他建议.
或者,您可以使用C#样式并将nextLine解析为整数,如下所示:
int number = Integer.parseInt(input.nextLine());
Run Code Online (Sandbox Code Playgroud)
这样做也很有效,它为您节省了一行代码.
Psh*_*emo 23
你需要知道的事情:
表示几行的文本也包含行之间的不可打印字符(我们称之为行分隔符)
"\r")"\n")当你从控制台读取数据时,它允许用户输入他的回复,当他完成时,他需要以某种方式确认这一事实.为此,用户需要按键盘上的"输入"/"返回"键.
重要的是,除了确保将用户数据放置到标准输入(由System.in哪个读取表示)之外,此键Scanner还会\r\n在其后发送OS相关行分隔符(如Windows ).
因此,当您向用户询问类似值age和用户类型42并按下Enter时,标准输入将包含"42\r\n".
Scanner#nextInt(和其他方法)不允许扫描仪使用这些行分隔符.它将从(扫描器如何知道用户没有更多的数字表示值而不是面向空格?)读取它们,这将从标准输入中删除它们,但它也会在内部缓存这些行分隔符.我们需要记住的是,所有Scanner方法始终都是从缓存文本开始扫描的. Scanner#nextTypeSystem.inage
现在Scanner#nextLine()只需收集并返回所有字符,直到找到行分隔符(或流的结尾).但是,由于在扫描程序的缓存中立即找到从控制台读取数字后的行分隔符,它会返回空字符串,这意味着扫描程序无法在这些行分隔符(或流结束)之前找到任何字符.
BTW nextLine也消耗那些行分隔符.
所以,当你要问的数量,然后整条生产线,同时避免了空字符串作为结果nextLine,无论是
nextInt扫描程序缓存中
剩余的行分隔符nextLine,skip("\\R")让扫描程序跳过匹配的\R代表行分隔符的部分(更多信息\R:https://stackoverflow.com/a/31060125)nextInt(也不next是或任何nextTYPE方法).而是逐行读取整个数据nextLine并使用每行解析数字(假设一行只包含一个数字)到适当的类型,如intvia Integer.parseInt.BTW:方法可以跳过分隔符(默认情况下所有空格,如制表符,行分隔符),包括扫描程序缓存的那些空格,直到它们找到下一个非分隔符值(标记).感谢代码输入Scanner#nextType"42\r\n\r\n321\r\n\r\n\r\nfoobar"
int num1 = sc.nextInt();
int num2 = sc.nextInt();
String name = sc.next();
Run Code Online (Sandbox Code Playgroud)
将能够正确分配num1=42 num2=321 name=foobar.
Cas*_*ldi 11
而不是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();
}
Run Code Online (Sandbox Code Playgroud)
如果要读取字符串和整数,则解决方案是使用两个扫描程序:
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();
Run Code Online (Sandbox Code Playgroud)
为了避免这个问题,请nextLine();立即使用,nextInt();因为它有助于清除缓冲区.当你按下ENTER了nextInt();不捕获新的生产线,因此,跳过Scanner以后的代码.
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
scanner.nextLine(); //clearing the buffer
Run Code Online (Sandbox Code Playgroud)
如果要快速扫描输入而不混淆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;
}
}
Run Code Online (Sandbox Code Playgroud)
ScanReader sc = new ScanReader(System.in);
3.导入必要的类:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
4.从main方法抛出IOException以处理异常5.使用提供的方法.6.享受
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....
Run Code Online (Sandbox Code Playgroud)
我想我参加派对已经很晚了..
如前所述,input.nextLine()在获得 int 值后调用将解决您的问题。您的代码不起作用的原因是因为没有其他东西可以从您的输入(您输入 int 的地方)存储到string1. 我将更详细地介绍整个主题。
将nextLine()视为Scanner 类中nextFoo()方法中的奇数。让我们举一个简单的例子..假设我们有两行代码,如下所示:
int firstNumber = input.nextInt();
int secondNumber = input.nextInt();
Run Code Online (Sandbox Code Playgroud)
如果我们输入下面的值(作为单行输入)
54 234
我们firstNumber和secondNumber变量的值分别变为 54 和 234。这样做的原因是因为当 nextInt() 方法接受值时,不会自动生成新的换行符(即 \n) 。它只需要“下一个整数”并继续前进。除了 nextLine() 之外,其余的 nextFoo() 方法也是如此。
nextLine() 在取值后立即生成一个新的换行符;这就是@RohitJain 所说的新换行被“消耗”的意思。
最后,next() 方法只获取最近的 String而不生成新行;这使其成为在同一行中获取单独字符串的首选方法。
我希望这会有所帮助.. 编码快乐!
小智 5
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
使用 2 个扫描仪对象而不是 1 个
Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
Run Code Online (Sandbox Code Playgroud)
如果我期望非空输入
避免:
– 如果以下输入被未经检查的scan.nextLine()作为解决方法吃掉
,则数据丢失 – 由于仅部分读取行而丢失数据,因为scan.nextLine()被替换为scan.next() (输入:“yippie yaye”)
– Exception使用Scanner方法解析输入时抛出的 s (先读,后解析)
public static Function<Scanner,String> scanLine = (scan -> {
String s = scan.nextLine();
return( s.length() == 0 ? scan.nextLine() : s );
});
Run Code Online (Sandbox Code Playgroud)
在上面的例子中使用:
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
Run Code Online (Sandbox Code Playgroud)
因为nextXXX()方法不读取newline,除了nextLine(). newline我们可以在读取任何值后跳过non-string(int在本例中),方法scanner.skip()如下:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(x);
double y = sc.nextDouble();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(y);
char z = sc.next().charAt(0);
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(z);
String hello = sc.nextLine();
System.out.println(hello);
float tt = sc.nextFloat();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(tt);
Run Code Online (Sandbox Code Playgroud)
在我的一个用例中,我遇到了读取前面有几个整数值的字符串值的情况。我必须使用“ for / while循环”来读取值。在这种情况下,上述建议都不起作用。
使用input.next()而不是input.nextLine()解决问题。希望这对处理类似情况的人有所帮助。
| 归档时间: |
|
| 查看次数: |
446245 次 |
| 最近记录: |