我想检查一个包含文字的JOptionPane
输入对话框"输入一个数字"是带有两个if语句的int或double。然后我想在一个if语句中转换int并在另一个中使用double执行相同的操作并打印"该数字是" (东西)。如果用户输入5,那么我希望它打印一个整数,如果用户输入5.3,那么我期望一个双倍。到目前为止,这是我的代码,如果你测试它,你会发现它不能用于我想要它做什么,但它运行:
int number1Int = 0;
double number1Double = 0.0;
String num1 = JOptionPane.showInputDialog("Enter a number");
if(number1Int == Integer.parseInt(num1)){
number1Int = Integer.parseInt(num1);
JOptionPane.showMessageDialog(null, "The number is " + number1Int);
}
else if(number1Double == Double.parseDouble(num1)){
number1Double = Double.parseDouble(num1);
JOptionPane.showMessageDialog(null, "The number is " + number1Double);
}
答案 0 :(得分:2)
您并没有完全提出问题,但我发现您的代码存在问题,我认为这可能是您遇到问题的原因。
您有if(number1Int == Integer.parseInt(num1))
仅当用户输入等于number1Int
的整数值时才会为真。由于number1Int
初始化为0,此条件为真的唯一时间是用户输入零形式,将解析为0 00,000等整数值
同样地,你也有else if(number1Double == Double.parseDouble(num1))
,只有当用户输入某种形式的零解析为双值时才是真的 - 可以是0.0,0.00,0000.000000等。
我猜你想要的更像是这样:
int number1Int = 0;
double number1Double = 0.0;
String num1 = JOptionPane.showInputDialog("Enter a number");
//EDIT: added boolean flag per comments
boolean isInt = false;
try{
number1Int = Integer.parseInt(num1);
isInt = true;
JOptionPane.showMessageDialog(null, "The number is " + number1Int);
}catch(NumberFormatException e){
System.out.println("User did not enter an integer.");
}
if(!isInt){
try{
number1Double = Double.parseDouble(num1);
JOptionPane.showMessageDialog(null, "The number is " + number1Double);
}catch(NumberFormatException e){
System.out.println("User did not enter a double.");
}
}