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;
}
}