2014-11-21 62 views
0

我无法找到我的程序中的任何问题。每次用户输入一个数字时,我都希望它将它保存在阵列A上,但是当用户尝试键入第二个数字时,会出现NumberFormatException错误。异常在线程“主”java.lang.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); 
     } 
    } 
} 
+2

有无你试过打印出'x'是什么? – APerson 2014-11-21 03:42:47

+1

对我来说可行... – MadProgrammer 2014-11-21 03:45:59

+1

这条线很有意义对于输入字符串:“”你不能将空字符串转换为整数 – 2014-11-21 03:46:30

回答

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 
0

它看起来像你试图输入你应该检查从堆栈跟踪空字符串,如果输入的是空的或不...

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); 
      } 
     } 
相关问题