扫描仪在使用next()或nextfoo()后跳过nextline()?

uubf1zoe  于 2021-07-03  发布在  Java
关注(0)|答案(21)|浏览(333)

我用的是 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() 以及 string2 = input.nextLine() 按我的意愿执行。

oyt4ldly

oyt4ldly1#

在我的一个用例中,我有这样一个场景:读取一个字符串值,后跟几个整数值。我必须使用“for/while循环”来读取值。而上述建议在这种情况下都不起作用。
使用 input.next() 而不是 input.nextLine() 解决了这个问题。希望这对处理类似情况的人有所帮助。

toe95027

toe950272#

如果我期望一个非空的输入

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
bnlyeluc

bnlyeluc3#

而不是 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();
}
wbrvyc0a

wbrvyc0a4#

问题在于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();
py49o6xq

py49o6xq5#

要解决此问题,只需执行scan.nextline(),其中scan是scanner对象的示例。例如,我用一个简单的hackerrank问题来解释。

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);
}

}

lxkprmvk

lxkprmvk6#

问题在于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();
a8jjtwal

a8jjtwal7#

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);
    }
0s0u357o

0s0u357o8#

如果您想快速扫描输入而不被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;
    }

}

优点:

扫描输入速度比bufferreader快
降低时间复杂性
为下一个输入刷新缓冲区

方法:

scanchar()-扫描单个字符
scanint()-扫描整数值
scanlong()-扫描长度值
scanstring()-扫描字符串值
scandouble()-扫描双值
scanint(int[]数组)-扫描整个数组(整数)
scanlong(long[]数组)-扫描整个数组(long)

用法:

将给定的代码复制到java代码下面。
初始化给定类的对象 ScanReader sc = new ScanReader(System.in); 3.导入必要的类: import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; 4.从主方法抛出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....
jvidinwx

jvidinwx9#

它这样做是因为 input.nextInt(); 没有抓住新线。你可以通过添加一个 input.nextLine(); 在下面。
或者,您也可以使用c#样式将下一行解析为整数,如下所示:

int number = Integer.parseInt(input.nextLine());

这样做同样有效,而且可以节省一行代码。

z2acfund

z2acfund10#

因为当你输入一个数字然后按回车键, input.nextInt() 只消耗数字,不消耗“行尾”。什么时候 input.nextLine() 执行时,它将使用第一个输入中仍在缓冲区中的“行尾”。
相反,使用 input.nextLine() 紧接着 input.nextInt()

bbuxkriu

bbuxkriu11#

使用此代码可以解决您的问题。

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)
wrrgggsh

wrrgggsh12#

使用两个扫描仪对象而不是一个

Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");    
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
hl0ma9xz

hl0ma9xz13#

作为 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);
k10s72fa

k10s72fa14#

那是因为 Scanner.nextInt 方法不会读取通过按“enter”创建的输入中的换行符,因此 Scanner.nextLine 在读了新行之后返回。
在使用时,您会遇到类似的行为 Scanner.nextLine 之后 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();

或者,更好的是,通读输入 Scanner.nextLine 把你的输入转换成你需要的格式。例如,可以使用 Integer.parseInt(String) 方法。

int option = 0;
try {
    option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
    e.printStackTrace();
}
String str1 = input.nextLine();
a1o7rhls

a1o7rhls15#

sc.nextLine() 比解析输入更好。因为从性能上看,它是好的。

相关问题