gpt4 book ai didi

Java当字段为空时抛出异常错误

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:19 24 4
gpt4 key购买 nike

当文本字段为空时,我遇到此异常,即使我检查其是否为空,它也会抛出异常错误。你能看一下这个方法并告诉我哪里出了问题吗?

private void addStaff()
{
ControlPanelCtr logCtr = new ControlPanelCtr();
String username = userField.getText();
String password = passField.getText();
int secLevel = Integer.parseInt(secLvField.getText());
if(userField.getText().equals("") || passField.getText().equals("") || secLvField.getText().equals(""))
{
notificationField.setText("All fields must be fullfiled.");
}
else
{
try{
Login usrObj = new Login();
if(usrObj.getUsername().equals(username))
{

}
else
{
Login logObj = new Login();
admLogIdField.setText(String.valueOf(logObj.getId()));
logCtr.addPeople(username, password, secLevel);
}
}
catch(Exception e)
{
notificationField.setText("Username already exists in the database.");
Toolkit.getDefaultToolkit().beep();
}
}
}

谢谢。

最佳答案

您确实检查了 secLvField 是否为非空,但为时已晚:您在尝试解析该字段以获取整数后检查该字段,这当然会抛出错误,因此支票永远不会到达。

这一行

int secLevel = Integer.parseInt(secLvField.getText());

secLevel为空或不代表有效整数时将抛出异常。您可以将解析包装在 try/catch block 中以查看是否成功:

int secLevel;
try {
secLevel = Integer.parseInt(secLvField.getText());
} catch (NumberFormatException nfe) {
secLevel = -1; // If -1 is valid, pick some invalid value
}
if (secLevel == -1 || userField.getText().equals("") || passField.getText().equals("")) {
notificationField.setText("All fields must be fullfiled.");
}
...

关于Java当字段为空时抛出异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23041944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com