[英]Why am I getting a NullPointerException when I try to read input using BufferedReader?
I am trying to take a multiple integer input in a single line and store all those integers into an ArrayList
.我正在尝试在一行中输入多个 integer 并将所有这些整数存储到
ArrayList
中。 This is my code:这是我的代码:
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));
The input is like this:输入是这样的:
2 2 1 3 1
2 2 1 3 1
But when I excecute the code I get a NullPointerException in this line input = br.readLine().split(" ");但是当我执行代码时,我在这一行得到 NullPointerException input = br.readLine().split(" "); .
. How can I fix this?
我怎样才能解决这个问题?
EDIT: Tried using Scanner to take the input like this:编辑:尝试使用扫描仪接受这样的输入:
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)); //[]
Now my array is completely empty!!现在我的数组完全是空的!!
You have two calls to br.readLine()
.您有两次调用
br.readLine()
。 While the first call will abort the loop if line is null, the second call can still read the next line which can be null (indicating end of file).如果行是 null,第一个调用将中止循环,第二个调用仍然可以读取可以是 null 的下一行(指示文件结束)。 Additional problem is also that the line returned by the first
br.readLine()
is lost.另一个问题是第一个
br.readLine()
返回的行丢失了。
The correct way is:正确的方法是:
String line;
while ((line = br.readLine()) != null) {
String[] input = line.split(" ");
}
There should be exactly 1 spaces between the input numbers.输入数字之间应该正好有 1 个空格。 Also you should not start input with space or have 2 spaces joined together when you are running this code.
此外,在运行此代码时,您不应以空格开始输入或将 2 个空格连接在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.