假设我有 3 个文本字段 - 用于用户输入值(当程序运行时):
TextField input1 = new JTextField("00");
TextField input2 = new JTextField("00");
TextField input3 = new JTextField("00");
当用户输入值时,程序会获取这些值并将它们存储为整数(用于稍后的操作):
public void actionPerformed(ActionEvent e) {
String temp1 = input1.getText();
String temp2 = input.getText();
String temp3 = input3.getText();
int num1=0, num2=0, num3=0;
if(e.getSource() == storeButton){
try{
num1 = Integer.parseInt(tem1);
num2 = Integer.parseInt(temp2);
num3 = Integer.parseInt(temp3);
}
catch(NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Input must be an integer from 0 to 50");
}
}
}
如上面的代码所示,当用户单击 storeButton 时,TextField 中的值将被解析为整数形式的特定变量,如果任何 TextField 包含整数以外的输入,则会显示一条消息将会弹出。
问题:
当调用异常时,如何清除(设置为“0”)不包含数字的TextField? 不得清除包含整数的文本字段。 我可以通过在解析为整数时对每个 TextField 使用 try 和 catch 来做到这一点,但这意味着代码重复太多(特别是当有很多 TextField 时)。
最佳答案
看一下Character.isDigit()。您可以创建一个子方法来循环每个字符串并检查它是否是数字。 或者,您可以在字符串上使用正则表达式来检查它是否是数字。 这使您可以摆脱 try/catch 并使用 if/else 处理它们。
关于java - 找到异常调用者并修改以显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33223741/