问题描述
我尝试了使用if语句的简单Java程序。
为此,我使用单选按钮检查是否选中?
请检查以下我的代码是否无法正常工作有人请帮助我吗?
以下项目链接
https://drive.google.com/file/d/1xhNbKyXYJh2k5i7a6nVl1VkTY7dTNzSg/view?usp=sharing
private void BTN_submitactionPerformed(java.awt.event.ActionEvent evt) {
String finalResult;
int age = Integer.parseInt(TXT_age.getText());
RBTN_male.setActionCommand("male");
RBTN_female.setActionCommand("female");
String radio_Result = BTNgrp_gender.getSelection().getActionCommand();
if (RBTN_male.isSelected() || RBTN_female.isSelected()) {
if (TXT_age.getText() == null || TXT_age.getText().trim().isEmpty()) {
JOptionPane optionPane = new JOptionPane("Please fill your age",JOptionPane.ERROR_MESSAGE);
jdialog dialog = optionPane.createDialog("Age missing");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
} else {
if (age == 0) {
JOptionPane optionPane = new JOptionPane("Please enter valid age",JOptionPane.ERROR_MESSAGE);
jdialog dialog = optionPane.createDialog("Wrong age");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
} else {
if (age > 0 && age <= 5) {
finalResult = "Rhymes";
LBL_result.setText(finalResult);
} else if (age > 15) {
finalResult = "Poetry";
LBL_result.setText(finalResult);
}
}
}
} else {
JOptionPane optionPane = new JOptionPane("Please Select Your Gender",JOptionPane.ERROR_MESSAGE);
jdialog dialog = optionPane.createDialog("Gender Missing");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
解决方法
代码的主要问题在于方法的第二行 BTN_submitActionPerformed
int age = Integer.parseInt(TXT_age.getText());
此处 TXT_age 的值为“输入您的年龄” 。现在无法将其解析为整数,因此将抛出 NumberFormatException ,这将阻止程序继续其预期的执行过程。该程序还会在单击时从该字段中删除占位符文本,使其为空,即“” ,因此提交该占位符文本也会导致错误。
要解决上述问题,您可以按以下方式重写此方法:
private void BTN_submitActionPerformed(java.awt.event.ActionEvent evt) {
int age;
String finalResult;
JOptionPane optionPane;
JDialog dialog;
RBTN_male.setActionCommand("male");
RBTN_female.setActionCommand("female");
try {
age = Integer.parseInt(TXT_age.getText());
if (RBTN_male.isSelected() || RBTN_female.isSelected()) {
if (age == 0 || age < 0 ) {
optionPane = new JOptionPane("Please enter valid age",JOptionPane.ERROR_MESSAGE);
dialog = optionPane.createDialog("Wrong age");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
} else {
if (age > 0 && age <= 5) {
finalResult = "Rhymes";
LBL_result.setText(finalResult);
} else if (age > 15) {
finalResult = "Poetry";
LBL_result.setText(finalResult);
}
}
} else {
optionPane = new JOptionPane("Please Select Your Gender",JOptionPane.ERROR_MESSAGE);
dialog = optionPane.createDialog("Gender Missing");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
} catch (NumberFormatException e) {
optionPane = new JOptionPane("Please fill your age",JOptionPane.ERROR_MESSAGE);
dialog = optionPane.createDialog("Age missing");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
在旁注中,您还可以想到可能出现的其他问题。例如,由于用户可以在文本字段中输入任何内容,这意味着用户可以输入可能不适合int的数字。因此,如果发生这种情况,您的程序将再次中断。但是,如果您对方法进行了上述更改,那么当前所面临的问题将得到解决。