读取整数或字符串时停止扫描器

Stop Scanner while reading Integers or String

我正在尝试使用扫描仪读取字符串,然后读取整数或字符串:

public class Main {
    public static void main (String[] args){
        String[] StringList; 
        Integer[] IntegerList;
        ArrayList<String> auxS = new ArrayList<>();
        ArrayList<Integer> auxI = new ArrayList<>();
        String order; int ord=-1;
        Scanner scan = new Scanner(System.in);
        order = scan.nextLine();
        //do something with order

        while(scan.hasNextLine()){
            if(scan.hasNextInt()){
                auxI.add(scan.nextInt());
            }
            else if(!scan.nextLine().isEmpty()){
                auxS.add(scan.nextLine());
            }else{ //I've tried using another scan. methods to get to this point
                scan.next();
                break;
            }
        }
    }
}

如您所见,我首先读取一个字符串并将其存储在“order”中,然后我想继续读取直到 EOF 或用户输入“Enter”或其他任何非特定的内容,例如“write 'exit'”或类似的东西。 我试过使用 scan.hasNext、hasNextLine 和涉及最后一个 else 的其他组合,但其中 none 有效。
如果输入是:

>>THIS WILL BE STORED IN ORDER<<
123
321
213
231
312
<enter>

我希望它在最后一行没有输入任何内容时停止。将整数或字符串存储在它们自己的 ArrayList 中很重要,因为我稍后会使用它并且我需要识别每个输入数据的类型(这就是我在 while 循环中使用 hasNextInt 的原因)。

一般情况下,不要使用 .nextLine(),它很混乱,而且很少能如愿以偿。如果您想将整行作为单个项目阅读,请更新扫描仪的定界符;将其从默认值 'any sequence of whitespace' 更改为 'a single newline':scanner.useDelimiter("\r?\n"); 会执行此操作(运行 会在制作扫描仪后立即执行)。要读取一行,请使用任何 .next() 方法(但不是 .nextLine()):想要一个 int 吗?打电话 .nextInt()。想要任何字符串?调用 .next(),等等。

然后拆分您的 if/elseif 块。一个空行仍然是一个字符串,只是一个空行:

if (scanner.hasNextInt()) {
    // deal with ints
} else {
   String text = scanner.next();
   if (!text.isEmpty()) {
       // deal with strings
   } else {
       // deal with a blank line
   }
}

注意:一旦您停止使用 .nextLine(),您就不必扔掉对 'clear the buffer' 或诸如此类的半随机 .nextLine() 调用。那种烦恼就消失了,这是您应该忘记 nextLine 的众多原因之一。一般来说,对于扫描仪,要么只使用 .nextLine(),要么永远不要使用 .nextLine(),这样会好很多。