简体   繁体   English

如何使用.nextInt .hasNextInt或.hasNext读取单行输入的整数而不会造成阻塞?

[英]How to read integers entered on a single line using .nextInt .hasNextInt or .hasNext without cause blockage?

I'm trying to read integers entered one after another on a single line separated by a space. 我正在尝试读取用空格分隔的一行中一个接一个输入的整数。 There will be some way for this code to work without using .nextLine , without converting the input to a string and then do the conversion to integer? 可以使用某种方式在不使用.nextLine情况下运行此代码,而无需将输入转换为字符串,然后转换为整数? The challenge is "not use .nextLine", do not use string or conversions. 挑战是“不使用.nextLine”,不使用字符串或转换。 Reading pure integers and exit from while loop. 读取纯整数并从while循环退出。

public static void scannerInts (){          
        int[] list = new int[100];
        int n=0;            
        System.out.print("Input data into one line, [ENTER] to finish: ");            
        Scanner input = new Scanner(System.in);
        while (input.hasNext()) {
            if (input.hasNextInt()) {
                list[n++]= input.nextInt();
            } else {
                input.next();
            }
        }
        for (int i=0;i<n;i++)
             System.out.print(list[i] + " ");
}

PD: I've tried many of the responses from Stack OverFlow and nothing seems to work. PD:我已经尝试了Stack OverFlow的许多响应,但似乎没有任何效果。

The problem is that System.in is an infinite stream. 问题在于System.in是无限流。 Calling hasNextXXX will cause System.in to prompt if the Scanner doesn't find a token in what has already been read. 调用hasNextXXX将导致System.in提示扫描程序是否在已读取的内容中找不到令牌。 The user needs to enter some non-integer to terminate the list. 用户需要输入一些非整数来终止列表。

You may, however, use a second Scanner since Scanner can scan a String eg: 但是,您可以使用第二台扫描仪,因为扫描仪可以扫描字符串,例如:

Scanner in = new Scanner(System.in);
System.out.print("Enter a list of integers: ");

List<Integer> list = new ArrayList<>();
Scanner line = new Scanner(in.nextLine());

// optional
line.useDelimiter("\\D+");

while(line.hasNextInt()) {
    list.add(line.nextInt());
}

System.out.println("You entered " + list);

Using a single Scanner you could also use findInLine : 使用单个扫描仪,您还可以使用findInLine

for(String token; (token = in.findInLine("-?[1-9]\\d*")) != null;) {
    list.add(Integer.valueOf(token));
}

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

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