运行 当我尝试使用 BufferedReader 将整数输入存储到数组时出现数字格式异常
Running into a number format exception when i'm trying to use the BufferedReader to store integer inputs into an array
我正在尝试使用 BufferedReader 接收多达 100 个输入,直到输入整数 1,然后程序终止。
public static void main(String[] args) throws IOException
{
//Instantiating an array of size 100, the max size.
int arrayOfInputs [] = new int[100];
//Creating the reader.
System.out.println("Enter some inputs");
BufferedReader BR = new BufferedReader (new InputStreamReader(System.in));
//Putting the inputs into a string.
String stringOfInputs = BR.readLine();
//Splitting the strings
String [] sOI = BR.readLine().split(" ");
for (int i = 0; i < sOI.length; i++)
{
//parsing the split strings into integers
if (Integer.parseInt(sOI[i]) != 0)
{
arrayOfInputs[i] = Integer.parseInt(sOI[i]);
System.out.print(arrayOfInputs[i] + " ");
}
}
}
我不明白为什么我的程序不工作。我正在读取输入,将其存储到一个字符串中,拆分字符串,然后将拆分的部分转换为整数,然后存储到我的大小为 100 的数组中。我做错了什么?
I am reading the input, storing it into a string, splitting the string, and then converting the split parts into integers to then store into my array of size 100.
您正在呼叫 BufferedReader#readLine()
两次。第一行被忽略,只处理第二行。您应该使用保存第一个读取行的变量:
String stringOfInputs = BR.readLine(); // TODO rename variable to use lowercase, e.g. br
//Splitting the strings
String [] sOI = stringOfInputs.split(" ");
...
我正在尝试使用 BufferedReader 接收多达 100 个输入,直到输入整数 1,然后程序终止。
public static void main(String[] args) throws IOException
{
//Instantiating an array of size 100, the max size.
int arrayOfInputs [] = new int[100];
//Creating the reader.
System.out.println("Enter some inputs");
BufferedReader BR = new BufferedReader (new InputStreamReader(System.in));
//Putting the inputs into a string.
String stringOfInputs = BR.readLine();
//Splitting the strings
String [] sOI = BR.readLine().split(" ");
for (int i = 0; i < sOI.length; i++)
{
//parsing the split strings into integers
if (Integer.parseInt(sOI[i]) != 0)
{
arrayOfInputs[i] = Integer.parseInt(sOI[i]);
System.out.print(arrayOfInputs[i] + " ");
}
}
}
我不明白为什么我的程序不工作。我正在读取输入,将其存储到一个字符串中,拆分字符串,然后将拆分的部分转换为整数,然后存储到我的大小为 100 的数组中。我做错了什么?
I am reading the input, storing it into a string, splitting the string, and then converting the split parts into integers to then store into my array of size 100.
您正在呼叫 BufferedReader#readLine()
两次。第一行被忽略,只处理第二行。您应该使用保存第一个读取行的变量:
String stringOfInputs = BR.readLine(); // TODO rename variable to use lowercase, e.g. br
//Splitting the strings
String [] sOI = stringOfInputs.split(" ");
...