繁体   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