我正在尝试编写一个try catch块,如果用户未输入名称而只是按enterokay,它将引发异常。我似乎遇到了问题,因为它没有抛出任何东西,只是接受了空白并继续。有人能帮我吗?提前致谢!

这是函数:

public String setOwnerName() {
        boolean isName = false;

        while(!isName) {
            try {
                this.ownerName = JOptionPane.showInputDialog(null, "Enter the account owner's name.", "Owner's Name", JOptionPane.PLAIN_MESSAGE);
                if(this.ownerName != "") {
                    isName = true;
                }
            } catch(IllegalArgumentException e) {
                JOptionPane.showMessageDialog(null, "Error you did not enter a name, please try again.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        return this.ownerName;
    }

最佳答案

空名称不会引发exception。您需要手动检查。尝试,

public String setOwnerName() {
  boolean isName = false;

while(!isName) {
 ownerName = JOptionPane.showInputDialog(null, "Enter the account owner's name.",
               "Owner's Name", JOptionPane.PLAIN_MESSAGE);

  if(ownerName.trim().isEmpty()){
    JOptionPane.showMessageDialog(null,
        "Error you did not enter a name, please try again.",
       "Error", JOptionPane.ERROR_MESSAGE);
  }
  else{
      isName = true;
      }
   }// end of while

    return ownerName;
}

09-12 11:17