Reputation: 33
I'm very new to java and trying to write a program for the user to enter a number and compare it to a set of rules. I have used parse.Int after JOptionPane, but when I try an 'if' statement I recieve a bad operand type; first type-string, second type-int. I don't understand since I used parse why it will not work. I know I'm missing something.
answer = 0;
while(answer == JOptionPane.YES_OPTION)
JOptionPane.showMessageDialog(null, " enter a number between 1-50", "by ...`enter code here`",
JOptionPane.PLAIN_MESSAGE);
String inputNumber;
inputNumber = JOptionPane.showInputDialog("Input an integer from one to 50: ");
Integer.parseInt(inputNumber);
if (inputNumber == 0 || inputNumber >= 51);
Upvotes: 0
Views: 125
Reputation: 905
See comments in the code. Additionally you need a try/catch or a throws arround the Integer.parseInt (don't know where you want to have it):
answer = 0;
while(answer == JOptionPane.YES_OPTION)
...
String inputNumber;
inputNumber = JOptionPane.showInputDialog("Input an integer from one to 50: ");
//replace:
//Integer.parseInt(inputNumber);
int number = Integer.parseInt(inputNumber);
//replace:
//if (inputNumber == 0 || inputNumber >= 51);
if (number == 0 || number >= 51);
Upvotes: 0
Reputation: 4201
Integer.parseInt
is a function, it will return the int
. The variable you passed as an argument, inputNumber
in this case, will remain a String
variable however. So you need to assing the result of Integer.parseInt
to a new variable of type int
and then use that variable for the comparisons.
Upvotes: 0
Reputation: 4574
It's because you're comparing a String (inputNumber) against an int value. Try this instead
int myint = Integer.parseInt(inputNumber);
if (myint == 0 || myint >= 51) {
...
}
Upvotes: 0
Reputation: 1500465
You're ignoring the return value of Integer.parseInt
. The inputNumber
is still a String
variable, not a number. I would rename it, to be clearer:
// This variable is the string representation...
String inputText = JOptionPane.showInputDialog("Input an integer from one to 50: ");
// ... and now inputNumber is the integer value parsed from inputText
int inputNumber = Integer.parseInt(inputText);
if (inputNumber < 1 || inputNumber > 50)
{
...
}
Note that Integer.parseInt
will throw an exception if the user doesn't enter an integer, but that's probably something to fix in a separate step...
Upvotes: 3