【发布时间】:2021-04-19 02:22:13
【问题描述】:
我试图在一行中输入多个整数并将所有这些整数存储到ArrayList 中。这是我的代码:
String[] input = new String[5];
ArrayList<Integer> A=new ArrayList<>(5);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
while(br.readLine()!=null)
input = br.readLine().split(" ");
}
catch(Exception e){
System.out.print(e);
}
System.out.println(Arrays.toString(input));
输入是这样的:
2 2 1 3 1
但是当我执行代码时,我在这一行 input = br.readLine().split(" "); 中得到一个 NullPointerException。我该如何解决这个问题?
编辑:尝试使用扫描仪接受这样的输入:
String str="";
Scanner s=new Scanner(System.in);
String[] input = new String[5];
ArrayList<Integer> A=new ArrayList<>(5);
while(s.hasNext())
str=s.nextLine();
input=str.split(" ");
System.out.println(Arrays.toString(input)); //[]
现在我的数组完全是空的!!
【问题讨论】:
-
在调用
split()之前测试readLine()的结果。 javadoc 解释了readLine何时返回null。 -
在运行此代码之前您是否关闭了
System.in? -
考虑为您的读者使用 try-with-resources 语句或 using 语句,具体取决于您的用例。
-
问题是您正在测试 readLine() 是否返回 null (eof),然后您再次调用 readlLine()。这第二个可能返回 null。你应该像
if ((str = br.readLine()) != null) { ... }一样进行测试。 -
试过@NomadMaker,错误依然存在
标签: java arraylist bufferedreader