[英]Exception in thread “main” java.lang.NumberFormatException: For input string: “” Array
I cant find any problems in my program. 我在程序中找不到任何问题。 Every time the user inputs a number, I want it to save it on the array A, but when the user tries to type the second number, the
NumberFormatException
error appears. 每次用户输入一个数字时,我都希望将其保存在数组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)
Here is the program: 这是程序:
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);
}
}
}
Code works absolutely fine, provided you enter only numbers. 只要输入数字,代码就可以正常工作。 If you enter empty string, it will give you the error what you have posted.
如果输入空字符串,它将给您错误已发布的内容。
Might need to add a check for empty string
. 可能需要
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]);
}
}
}
Output 输出量
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
it looks like you try to input an empty String from your Stacktrace you should check if the input is empty or not... 看来您尝试从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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.