我的程序中找不到任何问题。每次用户输入一个数字时,我希望它将其保存在数组A上,但是当用户尝试键入第二个数字时,会出现NumberFormatException
错误。
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at practice.test(end.java:22)
at end.main(end.java:7)
以下是该计划:
import java.io.*;
class end {
public static void main(String[] args) throws IOException {
practice obj = new practice();
obj.test();
}
}
class practice {
void test() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int A[] = new int[5];
String x;
int a, b, c, i = 0;
for(i = 0; i < 5; i++) {
System.out.println("Insert a number");
x = br.readLine();
A[i] = Integer.parseInt(x);
}
}
}
答案 0 :(得分:0)
只要输入数字,代码就可以正常工作。如果输入空字符串,它将显示您发布的错误。
可能需要add a check for empty string
。
if(!x.isEmpty()){
A[i] = Integer.parseInt(x);
}
public class end {
public static void main(String[] args) throws IOException {
practice obj = new practice();
obj.test();
}
}
class practice {
void test() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int A[] = new int[5];
String x;
int a, b, c, i = 0;
for (i = 0 ; i < 5 ; i++) {
System.out.println("Insert a number");
x = br.readLine();
A[i] = Integer.parseInt(x);
}
for (i = 0 ; i < 5 ; i++) {
System.out.println(A[i]);
}
}
}
<强>输出强>
Insert a number
2
Insert a number
3
Insert a number
4
Insert a number
5
Insert a number
6
User input
2
3
4
5
6
答案 1 :(得分:0)
看起来你试图从Stacktrace中输入一个空字符串,你应该检查输入是否为空......
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int A[] = new int[5];
String x;
int a, b, c, i = 0;
for(i = 0; i < 5; i++) {
System.out.println("Insert a number");
x = br.readLine();
//check if input is empty
if(!x.isEmpty()){
A[i] = Integer.parseInt(x);
}
}