[英]How to check if JOptionPane input contains an int or double with 2 if statements and is converted?
I would like to check if a JOptionPane
input dialog containing the text "Enter a number" is an int or double with two if statements. 我想检查包含文本“输入数字”的
JOptionPane
输入对话框是否为int或具有两个if语句的double。 Then I want to convert the int in one if statement and do the same thing in the other with a double and print "The number is" (something). 然后,我想在一个if语句中转换int,并在另一个中用double进行同样的操作,并打印“ The number is”(某物)。 If the user inputs 5 then I expect it to print an integer and if the user inputs 5.3 then I expect a double.
如果用户输入5,那么我希望它能打印一个整数;如果用户输入5.3,那么我希望它能打印一个整数。 Here is my code so far and if you test it you will see it does not work in terms of what I want it to do, but it runs:
到目前为止,这是我的代码,如果您对其进行测试,您会发现它无法按照我想要的方式运行,但可以运行:
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);
}
You didn't exactly ask a question, but I see a problem with your code that I think might be what you're having trouble with. 您没有确切提出问题,但是我发现您的代码有问题,我认为这可能是您遇到的问题。
You have if(number1Int == Integer.parseInt(num1))
which is only true if the user enters an integer value that is equal to number1Int
. 您拥有
if(number1Int == Integer.parseInt(num1))
,只有当用户输入等于number1Int
的整数值时,它才为number1Int
。 Since number1Int
is initialized to 0 the only time this condition is true is when the user enters a form of zero that will parse to an integer value like 0, 00, 000, etc. 由于
number1Int
初始化为0,因此只有当用户输入形式为0的形式时,此条件才为true,该形式将解析为整数值,例如number1Int
等。
Similarly you also have else if(number1Double == Double.parseDouble(num1))
which is only true when the user enters some form of zero that parses to a double value - could be 0.0, 0.00, 0000.000000 etc. 同样,您还具有
else if(number1Double == Double.parseDouble(num1))
,仅当用户输入某种形式的零以解析为双else if(number1Double == Double.parseDouble(num1))
值时才为true,可能为0.0、0.00、0000.000000等。
What I'm guessing you want is something more like this: 我猜您想要的是这样的东西:
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.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.