Im brand new to java, and I’m writing this short program where you guess a number between 1 and 10. The correct number is stored as an integer. If you guess a lower number, its supposed to say “The correct number is higher”, and if you guess a higher it should say “The correct number is lower”. Here’s what I have:
import javax.swing.*;
public class Oppg3 {
public static void main(String[] args) {
int number = 7;
int guessed = Integer.parseInt(JOptionPane.showInputDialog("Guess a number between 1 and 10"));
while(guessed>number) guessed = Integer.parseInt(JOptionPane.showInputDialog(guessed + " is wrong. Try a lower number."));
while(guessed<number) guessed = Integer.parseInt(JOptionPane.showInputDialog(guessed + " is wrong. Try a higher number."));
JOptionPane.showMessageDialog(null, guessed + " is correct!");
}
}
So obviously that wont work, cause if you enter a lower number it’ll jump to the next one, and that will come up as correct even if its higher. So how do I fix this so that it’ll check for both statements? Sorry for bad explaining. Thanks.
The simplest solution is to replace your current whiles with
ifs, and contain them both in a