I am creating a hangman code and i am done the basic code for my summative but i just need to add some small parts that i don't know how to do.
So the game i am creating is 2 player, first player enters the word and second player guesses. i made the code but i don't know how to restrict the first player from adding random characters into the secret word because for my project the word can only contain letters. so i need help making the code so the player 1 can only enter letters.
my code is below:
/**
* Auto Generated Java Class.
*/
import java.util.Scanner;
public class Hangman {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
String player1,player2;
int wrongguessamount = 0; //keeps the count of the amount of wrong guesses
int correctguessamount = 0; //keeps count of the amount of correct guesses
int maxincorrect=6;//makes sure the user cant guess more than 6 times
String a,b,c,d,e,f,g,h,i,j,k,l,m,n,p,q,r,s,t,u,v,w,x,y,z;
System.out.println("please enter a phrase player 1");
player1=input.nextLine();//player 1 enters the secret word
player1=player1.toLowerCase();//secret word get lower cased
for (int ii=0;ii < player1.length();ii++)
{
System.out.print("*");//the secret word is hidden with stars
}
char[] lettersreveal = new char[player1.length()];
for (int aa = 0; aa<lettersreveal.length; aa++) {
lettersreveal[aa] = '*';
}
System.out.println("player2 guess a character");
while ( wrongguessamount< maxincorrect&& correctguessamount<player1.length() )//player 2 starts guessing letters
{
String guess=input.nextLine();
int match = player1.indexOf(guess);//it takes the guessed letter and tries to find it in the secret word
if( match == -1){//if the guess is wrong it tells the user to guess again
System.out.println("Wrong guess, Try again");
wrongguessamount++;
}
if (match != -1) {
System.out.println("Correct guess");
lettersreveal[match] = guess.charAt(0); //matches and reveals the character guessed by player 2
correctguessamount++;
do{
match = player1.indexOf(guess, match+1);//as long as guess is a match it will continue unitl done
if (match != -1) {
lettersreveal[match] = guess.charAt(0);//if guess is correct it matches to word
correctguessamount++;
}//finsihes last if statement
}//closes do statement
while (match != -1);//while statement for the do statement
}//finishes first if statement
System.out.println(lettersreveal);
if( wrongguessamount==maxincorrect){
System.out.println("Sorry, you have reached 6 trys, GAME OVER");
}
}//finishes first while statementl
if(correctguessamount == player1.length()){
System.out.println("GOOD JOB, YOU GUESSED THE WORD");
}
}//closes main
}//closes class