How to start a Java program from where it was left after an error

85 Views Asked by At

In the program below, I created a simple number game that chooses a number between 1 and 100 and asks the user to guess the number. The user can continue guessing until they have made 10 attempts.

When I run the program and input a string, the program throws a NumberFormatException. After clicking ‘OK’, I couldn’t find a way to handle this, so I called the ‘TryAgain’ method. What I want to know is how to restart the program from the same number of attempts after I accidentally press a button with a string text.

import javax.swing.JOptionPane;

public class NumberGame {
    static int scoreOfWins = 0; 
    static int numberOfAttempt = 0;
    public static void main(String[] args) {
        Game();
    }

    static void Game() {
        try {
            int num = (int) (Math.random() * 100);
            int count = 10;
            while(count > 0) {
//              System.out.println(num);
                String inputTitle = "Guess the number between 1 to 100";
                String input = JOptionPane.showInputDialog(inputTitle, "Enter your answer here...");
                if (input == null) {
                    System.exit(0);
                }
                int intInput = Integer.parseInt(input);
                System.out.println(intInput);
                if (intInput == num) {
                    numberOfAttempt = 11 - count;
                    JOptionPane.showMessageDialog(null, "You win! Your guess was right after " + numberOfAttempt + " attempts");
                    scoreOfWins++;
                    TryAgain();
                    return;
                } else if (intInput > num) {
                    String numberOfTimes = " You can try " + (count - 1) + " times";
                    JOptionPane.showMessageDialog(null, "Your guess was not right! Please try Again with a lower value." + numberOfTimes);
                    count--;
                } else if (intInput < num){
                    String numberOfTimes = " You can try " + (count - 1) + " times";
                    JOptionPane.showMessageDialog(null, "Your guess was not right! Please try Again with a higher value." + numberOfTimes);
                    count--;
                }
            }
            JOptionPane.showMessageDialog(null, "You Lost the game!");
            TryAgain();
        } catch (Exception E) {
            JOptionPane.showMessageDialog(null, "Number format exception detected, Please only input numbers!");
            TryAgain();
        }
    }
    static void TryAgain() {
        while (true) {
            String inputAns = JOptionPane.showInputDialog("Type yes if you want to containue!"
                    + " Type No if you want to give up!", "you won " + scoreOfWins + " times do you want to continue?");
            if (inputAns == null) {
                System.exit(0);
            }
            inputAns = inputAns.toUpperCase();
            if (inputAns.equals("Y") | inputAns.equals("Yes")) {
                Game();
            } else if (inputAns.equals("N") |inputAns.equals("NO")) {
                JOptionPane.showMessageDialog(null, "OKAY you won " + scoreOfWins + " times today, see you later!");
                return;
            } else {
                JOptionPane.showMessageDialog(null, "Please provide a good valid identifier like Yes or NO");
            }
        }
    }
}
2

There are 2 best solutions below

0
Grinding For Reputation On

Here's your code doing what you want (probably not the most efficient way)

public class NumberGame {

    static int scoreOfWins = 0; 
    static int numberOfAttempt = 0;
    
    public static void main(String[] args) {
        game();
    }
    
    static int num = new Random().nextInt(100) + 1;
    static int count = 10;

    static void game() {
        try {
            while(count > 0) {
                String inputTitle = "Guess the number between 1 to 100";
                String input = JOptionPane.showInputDialog(inputTitle, "Enter your answer here...");
                if (input == null) {
                    System.exit(0);
                }
                int intInput = Integer.parseInt(input);
                System.out.println(intInput);
                if (intInput == num) {
                    numberOfAttempt = 11 - count;
                    JOptionPane.showMessageDialog(null, "You win! Your guess was right after " + numberOfAttempt + " attempts");
                    scoreOfWins++;
                    tryAgain();
                    return;
                } else if (intInput > num) {
                    String numberOfTimes = " You can try " + (count - 1) + " times";
                    JOptionPane.showMessageDialog(null, "Your guess was not right! Please try Again with a lower value." + numberOfTimes);
                    count--;
                } else if (intInput < num){
                    String numberOfTimes = " You can try " + (count - 1) + " times";
                    JOptionPane.showMessageDialog(null, "Your guess was not right! Please try Again with a higher value." + numberOfTimes);
                    count--;
                }
            }
            JOptionPane.showMessageDialog(null, "You Lost the game!");
            tryAgain();
        } catch (Exception e) {
            
            if(e instanceof NumberFormatException) {
                JOptionPane.showMessageDialog(null, "Number format exception detected, Please only input numbers!");
                game();
            }
            
            // Other exception handling here
        }
    }
    
    static void restart() {
        count = 10;
        game();
    }
    
    static void tryAgain() {
        while (true) {
            String inputAns = JOptionPane.showInputDialog("Type yes if you want to containue!"
                    + " Type No if you want to give up!", "you won " + scoreOfWins + " times do you want to continue?");
            if (inputAns == null) {
                System.exit(0);
            }
            inputAns = inputAns.toUpperCase();
            if (inputAns.equalsIgnoreCase("y") | inputAns.equalsIgnoreCase("yes")) {
                restart();
            } else if (inputAns.equalsIgnoreCase("n") |inputAns.equalsIgnoreCase("no")) {
                JOptionPane.showMessageDialog(null, "OKAY you won " + scoreOfWins + " times today, see you later!");
                return;
            } else {
                JOptionPane.showMessageDialog(null, "Please provide a good valid identifier like Yes or NO");
            }
        }
    }
}

• So first thing I fixed in your code was a small but good thing to practice and that is the naming conventions. It's pretty self explanatory.

• Secondly I switched out inputAns.equals("Yes") and inputAns.equals("NO") with inputAns.equalsIgnoreCase("yes") and inputAns.equalsIgnoreCase("no") which allows the user to type "yes" in anyway they want even "YeS".

• Next I implemented new Random().nextInt(100) + 1 which is probably a better way to generate random numbers. Here's a cool little question you might want to consider checking out if you wanna know more about this.

• I also checked what exception is thrown using instanceof so this allows you to manage more exceptions which you may find helpful later on.

I haven't in general changed a lot of your code except for removing num and count from your game method and making it a field. Now everytime you run the game method the count does not change it does only when you restart the game.

0
Reilas On

"... how to restart the program from the same number of attempts after I accidentally press a button with a string text. ..."

Here is an example.

import static java.lang.System.out;
Random r = new Random();
Scanner in = new Scanner(System.in);
String s;
int v = r.nextInt(1, 101), g, t = 0;
boolean exit = false;
do {
    out.print("guess:  ");
    s = in.nextLine();
    try {
        if (s.isBlank()) throw new Exception();
        g = Integer.parseInt(s);
        if (g != v) {
            out.print("wrong");
            if (++t != 10) out.printf(", %s tries remaining%n", 10 - t);
            else exit = true;
        }
        else {
            out.println("correct");
            exit = true;
        }
    } catch (Exception e) {
        out.printf("invalid input '%s', try again%n", s);
    }
} while (!exit);