2
\$\begingroup\$

I created a java number guessing game. I used some of the same code twice. I would like to know how to further simplify it if possible (I am a java beginner).

import java.util.Random;
import java.util.Scanner;

public class GuessingGameTest {

  public static void main(String[] args) {

    while (true) {
      System.out.println("Hello and welcome to my number guessing game.");

      System.out.println("Pick a number: ");

      Scanner inputnum = new Scanner(System.in);
      int maxnum;
      maxnum = inputnum.nextInt();

      while (maxnum > 100) {
        System.out.println("This is a big number, it will take you a while to guess.");
        System.out.println("Do you want to continue?");
        System.out.println("Type 0 for yes, type 1 for no.");
        Scanner inputnum1 = new Scanner(System.in);
        int largeNumber;
        largeNumber = inputnum1.nextInt();
        int yes1 = 0;
        int no1 = 1;

        if (largeNumber == yes1) {
          System.out.println("The game will continue.");

          Random rand1 = new Random();
          int number1 = rand1.nextInt(maxnum);
          int tries1 = 0;
          Scanner input1 = new Scanner(System.in);
          int guess1;
          boolean win1 = false;

          while (win1 == false) {

            System.out.println("Guess a number between 1 and " + maxnum + ": ");
            guess1 = input1.nextInt();
            tries1++;

            if (guess1 == number1) {
              win1 = true;

            } else if (guess1 < number1) {
              System.out.println("Number is to low, tray again");

            } else if (guess1 > number1) {
              System.out.println("Number is to high, try again");
            }
          }

          System.out.println("You win!");
          System.out.println("It took you " + tries1 + " tries.");
          System.out.println("Do you want to start again?");
          System.out.println("Type 1 to start again, type 2 to quit.");

          Scanner inputnumlast = new Scanner(System.in);
          int restartProgram1;
          restartProgram1 = inputnumlast.nextInt();
          int yes2 = 1;
          int no2 = 2;

          if (restartProgram1 == yes2) {
            System.out.println("The game will restart.");
            System.out.flush();
          }

          if (restartProgram1 == no2) {
            System.out.println("The game will quit.");
            System.exit(0);
          }
        }

        if (largeNumber == no1) {
          System.out.println("Pick a number below 100.");
          Scanner inputnum3 = new Scanner(System.in);
          int maxnum3;
          maxnum = inputnum3.nextInt();
        }
        break;
      }

      Random rand = new Random();
      int number = rand.nextInt(maxnum);
      int tries = 0;
      Scanner input = new Scanner(System.in);
      int guess;
      boolean win = false;

      while (win == false) {

        System.out.println("Guess a number between 0 and " + maxnum + ": ");
        guess = input.nextInt();
        tries++;

        if (guess == number) {
          win = true;

        } else if (guess < number) {
          System.out.println("Number is to low, tray again");

        } else if (guess > number) {
          System.out.println("Number is to high, try again");
        }
      }

      System.out.println("You win!");
      System.out.println("It took you " + tries + " tries.");
      System.out.println("Do you want to start again?");
      System.out.println("Type 1 to start again, type 2 to quit.");

      Scanner inputnum2 = new Scanner(System.in);
      int restartProgram;
      restartProgram = inputnum2.nextInt();
      int yes = 1;
      int no = 2;

      if (restartProgram == yes) {
        System.out.println("The game will restart.");
        System.out.flush();
      }

      if (restartProgram == no) {
        System.out.println("The game will quit.");
        System.exit(5);
      }

      while (maxnum > 100) {
        System.out.println("This is a big number, it will take you a while to guess.");
        System.out.println("Do you want to continue?");
        System.out.println("Type 0 for yes, type 1 for no.");
        Scanner inputnum1 = new Scanner(System.in);
        int largeNumber;
        largeNumber = inputnum1.nextInt();
        int yes1 = 0;
        int no1 = 1;

        if (largeNumber == yes1) {
          System.out.println("The game will continue.");

          Scanner inputnum0 = new Scanner(System.in);
          int maxnum2;
          maxnum = inputnum0.nextInt();
          Random rand1 = new Random();
          int number1 = rand1.nextInt(maxnum);
          int tries1 = 0;
          Scanner input1 = new Scanner(System.in);
          int guess1;
          boolean win1 = false;

          while (win == false) {

            System.out.println("Guess a number between 1 and " + maxnum + ": ");
            guess = input.nextInt();
            tries++;

            if (guess == number) {
              win = true;

            } else if (guess < number) {
              System.out.println("Number is to low, tray again");

            } else if (guess > number) {
              System.out.println("Number is to high, try again");
            }
          }

          System.out.println("You win!");
          System.out.println("It took you " + tries + " tries.");
          System.out.println("Do you want to start again?");
          System.out.println("Type 1 to start again, type 2 to quit.");

          Scanner inputnumlast = new Scanner(System.in);
          int restartProgram1;
          restartProgram1 = inputnumlast.nextInt();
          int yes2 = 1;
          int no2 = 2;

          if (restartProgram1 == yes2) {
            System.out.println("The game will restart.");
            System.out.flush();
          }

          if (restartProgram1 == no2) {
            System.out.println("The game will quit.");
            System.exit(0);
          }
        }

        if (largeNumber == no1) {
          System.out.println("Pick a number below 100.");
          Scanner inputnum3 = new Scanner(System.in);
          int maxnum3;
          maxnum = inputnum3.nextInt();
        }
        break;
      }

      Random randlast = new Random();
      int numberlast = randlast.nextInt(maxnum);
      int trieslast = 0;
      Scanner inputlast = new Scanner(System.in);
      int guesslast;
      boolean winlast = false;

      while (win == false) {

        System.out.println("Guess a number between 0 and " + maxnum + ": ");
        guess = input.nextInt();
        tries++;

        if (guess == number) {
          win = true;

        } else if (guess < number) {
          System.out.println("Number is to low, tray again");

        } else if (guess > number) {
          System.out.println("Number is to high, try again");
        }
      }

      System.out.println("You win!");
      System.out.println("It took you " + tries + " tries.");
      System.out.println("Do you want to start again?");
      System.out.println("Type 1 to start again, type 2 to quit.");

      Scanner inputnum3 = new Scanner(System.in);
      int restartProgram2;
      restartProgram2 = inputnum2.nextInt();
      int yeslast = 1;
      int nolast = 2;

      if (restartProgram == yeslast) {
        System.out.println("The game will restart.");
        System.out.flush();
      }

      if (restartProgram == nolast) {
        System.out.println("The game will quit.");
        System.exit(5);
      }
    }
  }
}
\$\endgroup\$

migrated from stackoverflow.com Jul 3 '17 at 9:05

This question came from our site for professional and enthusiast programmers.

  • \$\begingroup\$ I'd advise you to not to write everything inside a single method. In your case, you have put everything in the main(String[] args) \$\endgroup\$ – Jude Niroshan Jul 6 '17 at 3:39
  • \$\begingroup\$ How's my answer? Is there anything you would like to see change? \$\endgroup\$ – CodingNinja Jul 8 '17 at 4:11
3
\$\begingroup\$

I noticed that you had this piece of code repeated four times throughout your program.

  System.out.println("You win!");
  System.out.println("It took you " + tries + " tries.");
  System.out.println("Do you want to start again?");
  System.out.println("Type 1 to start again, type 2 to quit.");

One suggestion I would make is to insert this code into a method, that will you will only need to call the method and reduce the amount of code you have. For example you can do this:

public static void winningMessage(){

      System.out.println("You win!");
      System.out.println("It took you " + tries + " tries.");
      System.out.println("Do you want to start again?");
      System.out.println("Type 1 to start again, type 2 to quit.");
}

Then in your code just call the method, winningMessage();

Another suggestion I would make to your code is to only use one Scanner object. Within your code you have more than one when you only need one. You do not need multiple scanners for each time you are going to take user input you can continue to reuse the same scanner object.

Last suggestion I would make is to declare your variables up at the top of the program.

\$\endgroup\$
  • \$\begingroup\$ Thanks for the help! I would also want to know how I would prevent the user from entering a symbol or letter when asking for a number or guess. ex: (){}[] \$\endgroup\$ – Silent Beast Jul 3 '17 at 20:25
  • \$\begingroup\$ @SilentBeast you can try regular expressions or a try and catch method. \$\endgroup\$ – TheLearner Jul 5 '17 at 6:41
1
\$\begingroup\$

You have loaded all your code into the main() method. That is generally not good. You should aim to keep main() relatively small and have the workings hidden in other methods that you call from main(). Use main() more for flow control than for actually playing the game. Something like:

import java.util.Random;
import java.util.Scanner;

public class GuessingGameTest {

  // Shared class utilities.
  Random myRand = new Random();
  Scanner inScan = new Scanner(System.in);

  public static void main(String[] args) {

    // Introduce the game.
    System.out.println("Hello and welcome to my number guessing game.");

    // Play the game.
    boolean playing = true;
    while (playing) {

      // Play one game.
      playGame();

      // Another game?
      char reply = 'X';
      while (reply != '1' && reply != '2')
        System.out.println("Do you want to start again?");
        System.out.println("Type 1 to start again, type 2 to quit.");
        reply = inScan.nextChar();
      }

      if (reply == '2') {
        playing = false;  // Exit game.
      }
    }

    System.out.println("Thank you for playing.  Goodbye.");

  }

  static void playGame() {
    System.out.println("Pick a number: ");
    // Much code here.
  }

} // end class GuessingGameTest.

I have not compiled or tested this code, so test it thoroughly before using it.

Your use of exit() is not good practice either. Let the code finish naturally, and reserve exit() for exceptional situations, not for a normal termination.

\$\endgroup\$
  • \$\begingroup\$ Looks like you mixed this up a little with a different language. bool is called boolean in Java, also char reply = '#' won't work for inputting a number. Please do not give false information to the OP. \$\endgroup\$ – CodingNinja Jul 5 '17 at 6:11
  • \$\begingroup\$ Thanks for the correction on bool. The char reply = '#'; is just a dummy to trigger entry to the following while loop. Any character other than '1' or '2' would have done. The alternative was using a do ...while loop but I wasn't sure if the poster had covered them yet. \$\endgroup\$ – rossum Jul 5 '17 at 8:16
0
\$\begingroup\$

Welcome to Code Review, and thanks for sharing the code! Your code is alright for a beginner, but there is much work to do. Here are some things that will help in the future:

1. Use methods to avoid repeating code. Here are two examples which should help you:

Here's on for when the user wins:

   private static boolean playAgain(int correctNum) {
        boolean playAgain = false;
        System.out.println("You win! The number was " + correctNum);
        System.out.println("Would you like to play again(y/n)?");
        String play = inScan.next();
        if (play.equalsIgnoreCase("y")) {
            playAgain = true;
        }
        return playAgain;
    }

And here's one for guessing the number(until they guess it):

    private static boolean guess(boolean win, int guess, int number) {
        if (guess == number) {
            win = true;

        } else if (guess < number) {
            System.out.println("Number is to low, tray again");

        } else if (guess > number) {
            System.out.println("Number is to high, try again");
        }
        return win;
    }

2. You have a lot of unused variables

Your variables such as:
Random randlast, int numberlast, int trieslast, Scanner inputlast, int guesslast, boolean winlast, Scanner inputnum3, int restartProgram2, and many, many others are not used.

Note: You don't need to make a new Scanner for every input. Just declare one privately, and that's all you need. The same goes for Random, and most other java.util variables. Also, you do not need variables like yes, yes1, yes2 etc., just declare one variable yes privately and use it for all of your yes/no questions, and you will find much shorter code.

3. Your code indentation is poor

It looks like you've indented 2 spaces, however you are supposed to indent 4 spaces after every open brace. Check the JavaDocs

4. Don't use = or == for boolean varibles

Instead, do something like - while(!win)(while win is false), or while(win)(while win is true)

5. Give variables meaningful names

our variables have names that are not very helpful, such as number and largeNumber. Give them memorable names such as targetNum for the number to be guessed, and playAgain for if they want to play again or quit. yesNo is also popular for "play again" variables.

6. Your code is way longer than it needs to be

I have made the same program but a lot smaller. This should help you understand how to use methods, indent, write efficiently, and more. Check it out:

import java.util.Random;
import java.util.Scanner;

public class GuessingGameTest {
    private static Random rand = new Random();
    private static Scanner input = new Scanner(System.in);
    private static boolean quit = false;
    private static boolean win = false;
    private static int target;
    private static int tries;
    private static int highNum = 0;

    public static void main(String[] args) {
        while (!quit) {
            playGame();
        }
    }

    private static void playGame() {

        System.out.println("Hello and welcome to my number guessing game.");
        System.out.println("Pick a highest possible number: ");
        highNum = input.nextInt();

        if (highNum > 100) {
            System.out.println("This is a big number, it might take you a while to guess.");
            System.out.println("Do you still want to continue?");
            System.out.println("Type 0 for yes, type 1 for no.");
            int choice = input.nextInt();
            if(choice == 0) {

                target = rand.nextInt(highNum);
                guess(target);
            } 
            else {
                System.out.println("Pick a different number: ");
                highNum = input.nextInt();
                target = rand.nextInt(highNum);
                guess(target);
            }
        } else {
            System.out.println("Okay. Pick a number between 0 and " + highNum);
            target = rand.nextInt(highNum);
            guess(target);
        }
    }

    private static void guess(int randNum) {
        int guess = 0;
        while(!win) {
            guess = input.nextInt();
            if (guess == randNum) {
                win = true;

            } else if (guess < randNum) {
                System.out.println("Number is to low, try again");

            } else if (guess > randNum) {
                System.out.println("Number is to high, try again");
            }
            tries++;
        }
        playAgainMessage(guess);
    }

    private static void playAgainMessage(int correctNum) {
        System.out.println("You win! The number was " + correctNum);
        System.out.println("You got it in " + tries + " tries!");
        System.out.println("Would you like to play again(y/n)?");
        String play = input.next();
        if (play.equalsIgnoreCase("y")) {
            System.out.println("The game will restart.");
            System.out.flush();
            win = false;
            playGame();
        } else {
            System.out.println("The game will quit.");
            quit = true;
        }
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.