如何正确退出线程“ main”中的JOptionPanel异常java.lang.NumberFormatException:null

时间:2018-09-26 19:07:24

标签: java numberformatexception

我正在尝试创建一个GUI,用户必须在其中输入一个整数。如果用户输入非整数,则会提示GUI。我也希望它退出。当我退出它时,出现此错误:

  

线程“ main”中的异常java.lang.NumberFormatException:空。

我有点菜鸟,需要一些指导:)

const arr = [{ "children": [{ "property1": "1", "children": [{ "property1": "p1", "children": [{ "property1": "p11", "children": [ ] }] }] }] }, { "children": [{ "property1": "2", "children": [{ "property1": "p2", "children": [{ "property1": "p21", "children": [ ] }] }] }] } ];

function getProperty(arr, result){
  for(var i = 0; i < arr.length; i++){
    if(arr[i].property1)
      result.push(arr[i].property1);
    if(arr[i].children && arr[i].children.length)
      getProperty(arr[i].children, result);
  }
}
let result = [];
getProperty(arr,result)
console.log(result);

3 个答案:

答案 0 :(得分:0)

问题是您从try / catch块中留下了可能会导致异常(int analysisLevel = Integer.parseInt(input);)的一行。您需要将其移入内部:

String input = JOptionPane.showInputDialog("Enter Desired Analysis level");
try
{
    int analysisLevel = Integer.parseInt(input);
    if (analysisLevel >= 0) {
        System.out.println(analysisLevel);
    } else {
        input = JOptionPane.showInputDialog("Enter Desired Analysis level");
    }
}
catch (Exception e)
{
    System.out.println("Input was no number. " + e);  
}

此外,您不需要System.exit(0);,因为程序仍会退出,因此使用System.exit(0);通常不是一个好习惯。

答案 1 :(得分:0)

您正在打印出catch块中的错误-尝试将非整数解析为Integer时,将引发NumberFormatException。唯一的问题是引发错误的行不在try块中。

答案 2 :(得分:0)

尝试一下。这利用了例外:

public static void main(String[] args) {
    String input = JOptionPane.showInputDialog("Enter Desired Analysis level");
    try {
        int analysisLevel = Integer.parseInt(input);
        //Code you want to run when analysisLevel is a number
        if (analysisLevel >= 0) {
            System.out.println(analysisLevel);
        }
    } catch (NumberFormatException nfe) {
        //Code you want to run when analysisLevel isn't a number
        input = JOptionPane.showInputDialog("Enter Desired Analysis level");
    }
    System.exit(0);
}
相关问题