在 JOptionPane 上停止堆栈跟踪

Stopping stacktrace on a 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 是双重等价物。

您正在比较字符串,因此您应该使用

而不是 amountEntered != ""
!amountEntered.equals("");

只要您想比较 Java 中的字符串 ...

,这就适用

especially 为空尝试 string == null

你的逻辑有点不对,首先,在 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 amountEntered为空amountEntered.isEmpty()不会被执行