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

wooyq4lh  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(254)

我正在尝试读取一个字符串,然后使用scanner读取整数或字符串:

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

如您所见,我首先读取一个字符串并按“顺序”存储,然后我想继续读取,直到eof或用户输入“enter”或其他非特定的内容,如“write”“exit”或类似的内容。我尝试过使用scan.hasnext、hasnextline和其他涉及最后一个else的组合,但都不起作用。
如果输入为:

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

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

z4bn682m

z4bn682m1#

一般来说,只是不要使用 .nextLine() ,这是混乱的,很少做你想做的事。如果要将整行作为单个项目读取,请更新扫描仪的分隔符;将其从默认的“任意空格序列”更改为“单个换行符”: scanner.useDelimiter("\r?\n"); 会这样做(做扫描仪后立即运行)。要读一行,请使用 .next() 方法(但不是 .nextLine() ):要整数吗?呼叫 .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() ,你不必抛出半随机 .nextLine() 呼叫“清除缓冲区”或诸如此类。这种烦恼就这样消失了,这也是为什么你应该忘记nextline的原因之一。一般来说,对于扫描仪,要么只使用 .nextLine() ,或者永远不要使用 .nextLine() ,事情会好很多。

相关问题