So I have to create a guessing game to be played between 2-5 players. That part wasn't very difficult. I am however having LOTS of trouble with the try...catch statement. I have to have to make the program have a try catch so it doesn't throw an error if the input typed by the user is invalid. Also, I'm having some trouble getting my "play again" method to work. Any help is appreciated. Thank you.

import java.util.*; 
 
    public class g { 
     
        public static void main(String[] args) { 
     
            boolean play = true; 
         
            String answer = "y"; 
            String playAgain; 
            Scanner in = new Scanner(System.in);
            Scanner input = new Scanner(System.in);
            int y = 1; 
            int a = 0;
             
        while (true){ 
     
            int [] random ; 
            random = new int[6]; 
     
            boolean [] won ; 
            won = new boolean [6]; 
     
            int counter=0; 
            boolean stopPlay = false; 
     
            System.out.println ("How Many players are there?"); 
            int player = in.nextInt(); 
     
            for (int x = 1; x<= player; x++){ 
                random[x] = getNumber(); 
    } 
     
        while(!stopPlay){ 
            counter++; 
            int[] guesses = new int[player]; 

            System.out.println("Guess a number between 1 and 100"); 
            for(int i=1; i<=player; i++){ 
                guesses[i-1]= getGuess(i); 
    } 
            for(int i=1; i<=player; i++){ 
                System.out.print("Player " + i + ", your guess is "); 
                won[i]= compare(guesses[i-1], random[i], counter); 
                if (won[i] == true){ 
                break; 
    } 
    } 
     
    } 
        System.out.println ("Play again: (y/n)"); 
        answer = in.nextLine(); 
        while (play==true); 
        if (answer=="yes" || answer == "y"){ 
            play = true; 
             
        } else if (answer == "no" || answer == "n"){ 
            play = false; 
        } 
         
        } 
             

     
    } 
     
        public static int getNumber (){    
            Random generator = new Random(); 
            boolean check=false;
            int a = generator.nextInt(100)+1; 
            String myString= "a";
            Scanner input = new Scanner(System.in);

            try{
                System.out.print("Type your first number: ");
                a = input.nextInt();
                check = true;
                }
                catch (java.util.InputMismatchException x) {
                System.out.println("Invalid input! Please type an Integer. ");
                a = 0;
                check = false;
                input.nextLine();
                }
            return getNumber();
    } 

        public static int getGuess(int i){ 
     
            Scanner in = new Scanner(System.in); 
            System.out.print("Player " + i + ": "); 
            int guess = in.nextInt(); 
            return guess; 
    } 

        public static boolean compare(int guess, int random, int count){ 
             
             
            if(guess < random){ 
                System.out.println("Too Low"); 
    } 
            if(guess > random){ 
                System.out.println("Too High"); 
    } 
            if (guess == random){ 
                System.out.println("Correct!"); 
                System.out.println("The number of guesses: " + count); 
                 
                System.out.println("You Win!");             
     
            return true; 
    } 
        else return false; 
    } 

    }

Recommended Answers

All 3 Replies

Hmm... There are so many things to talk about your code... But I will keep it for your later improvement of your own code.

Anyway, when you want to keep looping for playing, you need the while-loop to cover the whole part from random guessing numbers (and why numbers anyway???) until the game is won.

Also, there are couple things to look at.
1) Comparing string should use equals() method, not "==" symbol.

if (answer.equals("yes") || answer.equals("y")) {
  ...
}
// or if you want case-insensitive
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
  ...
}

2) if (won==true) is the same as if(won).

commented: thanks +1

Okay thanks. I got the loop to work know.
Any ideas on the try catch? I'm still confused on how it works.

public static int getNumber (){
Random generator = new Random();
boolean check=false;
int a = generator.nextInt(100)+1;
String myString= "a";
Scanner input = new Scanner(System.in);
 
try{
System.out.print("Type your first number: ");
a = input.nextInt();
check = true;
}
catch (java.util.InputMismatchException x) {
System.out.println("Invalid input! Please type an Integer. ");
a = 0;
check = false;
input.nextLine();
}
return getNumber();
}

Do you want to keep accepting an input until it is valid? If so, there are things you need to do...

1)You need to return a valid integer value entered by a user, not another method call which causes an infinite loop.
2)You do not need to initial the variable "a" or you could initial it to 0 if needed.
3)You do not need "check" variable if the entered value from a user must be a positive integer.

int a = 0;
  ...
  while (a<=0) { // "a" must be a positive integer in order to get out of the loop
    try {
      System.out.print("Type your first number: ");
      a = input.nextInt();
      // if a user enters an invalid value to the line above, the "catch" block will be executed instead
      // if the user enters a valid value, it will ignore the catch block and get out of the while-loop
    }
    catch (java.util.InputMismatchException x) {
      System.out.println("Invalid input! Please type a positive integer.");
      a = 0;  // reset "a" value to keep the loop alive
      // because we do nothing else but reset the value of "a" variable, the loop goes on
    }
  }
  // if the code can execute to this line, it means that a valid integer is entered, return it
  return a;

PS: All methods but "main()" in your code do not need be "static" at all. You could simply use "public int ..." or something like that instead of "public static int ..."

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.