I'm making a program where you type in a number and it will either tell you if you got it right or wrong. This is the code.
static int num = 1;
JPanel pnl = new JPanel();
JTextField numSlot = new JTextField(5);
pnl.add(new JLabel("Enter the number:"));
pnl.add(numSlot);
int k = JOptionPane.showConfirmDialog(null, pnl, "Enter your code", -1);
if (k == JOptionPane.OK_OPTION) {
if(numSlot.getText().equals(num)) {
JOptionPane.showMessageDialog(null, "It Worked", "It Worked", -1);
} else {
JOptionPane.showMessageDialog(null, "Sorry", "Sorry", -1);
}
}
if (k == JOptionPane.CANCEL_OPTION) {
} else {
}
With this code it always outputs sorry even if i type 1 so is there something i'm doing wrong? If so could you answer it and try not to be rude i am a beginner.
use
if(numSlot.getText().equals(num+"")){
instead of
if(numSlot.getText().equals(num)) {
as num+""
convert it int
to String
.
Otherway you can use Integer.toString(num)
or String.valueOf(num)
Explanation
numSlot.getText()
return String and num
is int so numSlot.getText().equals(num)
always false as String value can not be same as integer value.