2014-11-21 44 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); 
      } 
     } 
相關問題