【发布时间】:2021-03-06 20:15:45
【问题描述】:
我正在尝试使用扫描仪读取字符串,然后读取整数或字符串:
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 的原因)。
【问题讨论】:
-
您可以使用 BufferedReader 获得更多控制权。
标签: java input while-loop java.util.scanner