簡體   English   中英

線程“ main”中的異常java.lang.NumberFormatException:對於輸入字符串:“” Array

[英]Exception in thread “main” java.lang.NumberFormatException: For input string: “” Array

我在程序中找不到任何問題。 每次用戶輸入一個數字時,我都希望將其保存在數組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);
        }
    }
}

只要輸入數字,代碼就可以正常工作。 如果輸入空字符串,它將給您錯誤已發布的內容。

可能需要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

看來您嘗試從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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM