Search code examples
javajoptionpane

Replay the app from the start, how to?


Im new to Java and all this. But I got this code and the thing I want to do is if I got a "Yes_No_Option" and then If the user presses "yes" it will restart the code from the start", and if the user presses "no" it will just close. thanks to all answers!

public class JOptionMain {
     static Scanner sf = new Scanner(System.in);
     static String low,high, guessStr;
     static int x, y, guess, rnd;

public static void main(String[] args) {
    low = JOptionPane.showInputDialog("Enter the lowest number: ");
    high = JOptionPane.showInputDialog("Enter the highest number: ");
    try{
        x = Integer.parseInt(low);
        y = Integer.parseInt(high);
        guessStr = JOptionPane.showInputDialog("Guess the number between " + x + " and " + y);
        guess = Integer.parseInt(guessStr);
    }catch(NumberFormatException e){
        JOptionPane.showMessageDialog(null, "You entered something wrong, app will now exit!" , "Error", JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }
    rnd = randomGen(y, x);
    boolean bool = check(guess, rnd);
    if (bool == true){
        JOptionPane.showMessageDialog(null, "Congrats! You entered the correct number", "Correct", JOptionPane.INFORMATION_MESSAGE);
    }else{
        JOptionPane.showMessageDialog(null, "Im Sorry, you entered the wrong number. The correct number was " + rnd);
    }
} //For Main

public static int randomGen(int high, int low){
    int random = (int)(Math.random()*(high - low + 1) + low);
    return random;
}

public static boolean check(int num1, int num2){
    if(num1 == num2){
        return true;
    }else{
        return false;
    }
}

} //For the whole


Solution

  • You could surround your main code with a while loop checking a Boolean value which you initialize to true. when the user says no, switch that value to false and the program will exit the while loop, or when they say yes, just do nothing and the flow of the program should restart at the beginning of the while loop.