简体   繁体   中英

Letter guessing game Java

I have been working on a java guessing game for letters (az), However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2.....z = 26!

I want the user to try and guess the letter and not the number, but i cannot workout how to do this!

(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)

Random r = new Random();

char targetLetter = (char)(r.nextInt(26) + 'a');       

Any help would be greatly appreciated! And i can display my code if it is needed

public class Stack {

    public static void main(String[] args) {

        Random rand = new Random(); //This is were the computer selects the Target

        int guess;
        int numGuesses = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int bestScore = 0;

        Scanner consoleIn = new Scanner(System.in);
        Scanner name = new Scanner(System.in);

        System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
        userName = name.nextLine();

        System.out.println("Hello " + userName + " :) Welcome to the game!\n");


        while (play = true) {
            session++;
            Target = rand.nextInt(26) + 1;
            System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                numGuesses++;

                if (guess > 26)
                    System.out.println("Error! Above MAXIMUM range");
                else if (guess <= 0)
                    System.out.println("Error! Below MINIMUM range");
                else if (guess > Target)
                    System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
                else if (guess < Target)
                    System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
            } while (guess != Target && numGuesses < 5);

            if (guess == Target) {
                System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
            } else {
                System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
                if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
                    play = true;
                    numGuesses = 0;
                } else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
                    play = false;
                    System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
                    System.out.println("You had  " + session + " Goes");
                    System.out.println("The number of times you guessed correctly: " + sessions + "");
                    break;
                }
            }
        }
    }
}

use arrays of characters

char[] chars = ['A','B','C'...];

and use the random numbers to map to each character

char targetLetter = chars[r.nextInt(26)];
 public static void main(String args[])
        {
            Scanner scan = new Scanner(System.in);      
            System.out.println("Guess the Letter");
            String myLetter=scan.nextLine();
                //get the letter of myLetter variable then convert to Uppercase
            char enteredLetter=Character.toUpperCase(myLetter.charAt(0));
                    //26 only because the characters array starts with index 0
            char[] characters ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
                    //I had created a parrallel array symbolizing int value of each letter
            int[] range={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
            //this variable convert user input to one of the array element of range
            int userInputToInt=0;
            //this variable is for knowing what int[] range array element must the value of userInputToInt fall
            int userInputControlLoop=0;
            char randomLetter=characters[(int)(Math.random()*26)];
            // get the random input of computer convert it to int
            int computerInputToInt=0;

                //this loop is for getting the int value of randomLetter input by the computer
                for(int i=0;i<characters.length;++i)
                {
                    if(randomLetter==characters[i])
                    {

                        computerInputToInt=range[i];
                    }
                }
                //this loop is for getting the int value of user inputted letter
                for(char i:characters)
                {
                    if(enteredLetter==i)
                    {
                        userInputToInt=range[userInputControlLoop];
                    }
                    ++userInputControlLoop;
                }


                 //test the entered letter of user
            if(enteredLetter==randomLetter)
            {
                System.out.println("Correct Guess");
                System.out.println("The letter is:"+randomLetter);
            }
            //test the entered letter of user if greater than computer input
            else if(userInputToInt>computerInputToInt)
            {
                System.out.println("Incorrect Guess");
                System.out.println("The letter is too high");
                System.out.println("The letter is:"+randomLetter);
            }
            //test the entered letter of user if lesser than computer input
            else if(userInputToInt<computerInputToInt)
            {
                System.out.println("Incorrect Guess");
                System.out.println("The letter is too low");
                System.out.println("The letter is:"+randomLetter);
            }

        }

Use the same method that you do for your random characters. Assuming you have your guessed character as an int variable called "guess", and it has value 1-26 corresponding AZ:

Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');

...

int guess = ...
char guessChar = (char)guess + 'a';
if (guessChar == targetLetter) { 
    System.out.println("Correct!");
} else {
    System.out.println("Guess again!")
}

You can implement it in this approach :

1- Create a String alphabet with the characters that you want.

2- declare the size of alphabet as n variable which will control the random generator range.

3- alphabet.charAt(random.nextInt(n)) is a random char from the alphabet.

program code will be :

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int n = alphabet.length();

Random r = new Random();  

System.out.println(alphabet.charAt(r.nextInt(n)));

hope will help solve your problem.

public class Picnic1 {
    // RULE 0: This code is provided as a working example.
    // This rule tests for whether a word starts with the letter 'b' (allowed to the picnic).
    public static boolean rule0(char[] array) {
        if (array[0] == 'b') {
            return true;
        }
        else {
            return false;
        }

        // itemMessage:
        // Return message about whether a particular item is allowed to the picnic.
        public static String item ( double[] a){
            // This code works, providing output like these examples:
            //   "banana: true"
            //   "collie: false"
            // It needs to be replaced with a more suitable output.
            // Instead it should return, for example:
            //   "Yes, you can bring a banana to the picnic."
            //   "No, you cannot bring a collie to the picnic."
            if (a[0] == 'b') {
                System.out.println("Yes, you can bring a" + 'a' + "to the picnic");
            }
            else if (a[0] != 'b') {
                System.out.print("No, you can not bring a " + 'a' + "to the picnic");
            }

        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM