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.
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
.
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...
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.