我正在尝试编写一个try catch块,如果用户没有输入名称而只是按enter
或okay
我将会抛出异常,因为它没有抛出任何它只是接受空白并继续。有人能帮我吗?提前谢谢!
这是功能:
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;
}
答案 0 :(得分:1)
空名称不会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;
}
答案 1 :(得分:0)
这样做
try{
if(ownerName.trim().isEmpty())
{
throw new IllegalArgumentException("Input is wrong");
}
} catch(IllegalArgumentException e) {
}