在JOptionPane上停止堆栈跟踪

时间:2015-03-16 18:09:57

标签: java nullpointerexception null stack-trace joptionpane

我正在尝试停止一个似乎没有听我的空检查的堆栈跟踪。

          if(amountEntered != null){

                   amntEntered = Double.parseDouble(amountEntered);       
            }

            else if(amountEntered != ""){

                amntEntered = Double.parseDouble(amountEntered);
            }

            else if((amountEntered == null || amountEntered == "")){
             System.out.print("");    
            }

使用此代码,它应该停止在我尝试取消JOptionPane时执行的堆栈跟踪(amountEntered是分配JOptionPane的变量) - amntEntered是双重等价。

2 个答案:

答案 0 :(得分:1)

您正在比较字符串,而不是amountEntered != ""您应该使用

!amountEntered.equals("");

只要您想在Java ...

中比较字符串,就会应用

especially 等于null,请尝试string == null

答案 1 :(得分:0)

您的逻辑有点偏离,首先,在Java String中使用equals(..)进行比较:

if(amountEntered != null){
      amntEntered = Double.parseDouble(amountEntered);  
      // Because you are comparing amountEntered to "" and you check if it's null
      //I assume it is of type String which means that you can't cast it to a double.
}else if(!amountEntered.equals("")){ 
        // if it gets past the first check
        // it means that amountEntered is null and this will produce a NullPointerException
    amntEntered = Double.parseDouble(amountEntered);
}else if((amountEntered == null || amountEntered.equals(""))){
        // Here if amountEntered is null, the second check will
        // still be executed and will produce a NullPointerException
        // When you use || both the check before || and after || are executed
    System.out.print("");    
}

以下是执行检查和处理任何Exception的方法:

if(amountEntered != null && !amountEntered.isEmpty()){
   try{
      someDoubleVariable = Double.parseDouble(amountEntered);
   }catch(NumberFormatException e){
      someDoubleVariable = 0;
      e.printStackTrace()
   }
}else if(amountEntered==null || (amountEntered!=null && amountEntered.isEmpty())){
     someDoubleVariable = 0;
}

在此示例中,由于我使用&&,因此只要其中一个false,条件检查就会停止,这意味着在else if if {{} 1}}为空amountEntered将不会被执行