简体   繁体   中英

“while loop” in Letter Guessing game Java

I am trying to make Letter guessing Game, in which user needs to guess Letter Between A - Z, and if guessed letter is incorrect, it says that letter is higher or lower than guessed. I made a code, which does it correctly, but I cant add loop, which will repeat code until user guesses right letter. I am novice, so a bit of explanation and help would be very nice.

Here's my code:

import java.util.Scanner;

public class GuessTheLetter {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Guess the Letter");
        String myLetter = scan.nextLine();
        char enteredLetter = Character.toUpperCase(myLetter.charAt(0));
        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 };
        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' };
        char randomLetter = characters[(int) (Math.random() * 26)];
        int userInputToInt = 0;

        int userInputControlLoop = 0;

        int computerInputToInt = 0;

        for (int i = 0; i < characters.length; ++i) {
            if (randomLetter == characters[i]) {
                computerInputToInt = range[i];
            }
        }

        for (char i : characters) {
            if (enteredLetter == i) {
                userInputToInt = range[userInputControlLoop];
            }
            ++userInputControlLoop;
        }

        if (enteredLetter == randomLetter) {
            System.out.println("Correct Guess");
            System.out.println("The letter is:" + randomLetter);
        }

        else if (userInputToInt > computerInputToInt) {
            System.out.println("Incorrect Guess");
            System.out.println("The letter is too high");
            System.out.println("The letter is:" + randomLetter);
        }

        else if (userInputToInt < computerInputToInt) {
            System.out.println("Incorrect Guess");
            System.out.println("The letter is too low");
            System.out.println("The letter is:" + randomLetter);

            scan.close();
        }

    }
}

This is what you want:

import java.util.Scanner;

public class GuessTheLetter {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Guess the Letter:-\n");

        char randomLetter = (char) (Math.random() * 26 + 65); // logic to generate random letter

        char enteredLetter = 0; // initializing variable to store entered letter

        while (true) {// infinite loop till correct guess
            System.out.print("\nEnter your Guess : ");
            enteredLetter = Character.toUpperCase(scan.next().charAt(0)); // emter letter
            if (enteredLetter == randomLetter) {
                System.out.println("Correct Guess");
                System.out.println("The letter is:" + randomLetter);
                break;// exit loop if correct letter is guessed
            } else if (enteredLetter > randomLetter) // we can directly compare char like int
            {
                System.out.println("Incorrect Guess");
                System.out.println("The letter entered is too high");
            }

            else if (enteredLetter < randomLetter) // we can directly compare char like int
            {
                System.out.println("Incorrect Guess");
                System.out.println("The letter entered is too low");
            }

        }
        scan.close();
    }

}

Explanations are in comments of the program!

Solution

Here is the Updated Code with this Boolean Variable like in the comment section mentioned.

But you also have to consider maybe add an try / catch / finally block and then in the finally block part close your scanner(finally will always be invoked)

Because you now loop until you have the right guess you have to create the random variable outside of the loop, otherwise it would create in each iteration a new random character.

Also I get rid of these control loops, actually a great benefit working with char is you can compare there ASCII Value to other chars.

Here where we just comparing the characters in Uppercase we can directly compare these characters to each other with enteredLetter > randomLetter for example.

Example:

enteredLetter = 'A';
randomLetter = 'D';
enteredLetter > randomLetter

This comparison would check ASCII Value A=65 > D=69 SO A is not greater than D and go to the next condition.

Also you should check for valid input with Characters the way should be the static Method of class characterisLetter() . Also don't take input as string instead take the input directly as character with char myLetter = scan.next().charAt(0);

package hall;

import java.util.Scanner;

public class GuessingGame {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Boolean isGuessed = false;
        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' };
        char randomLetter = characters[(int) (Math.random() * 26)];

        while (!isGuessed) {

            System.out.println("Guess the Letter");
            char myLetter = scan.next().charAt(0);
            if(!(Character.isLetter(myLetter))) {
                System.out.println("Invalid Input Try Again:");
            }else {
                
            
            char enteredLetter = Character.toUpperCase(myLetter);



            if (enteredLetter == randomLetter) {
                System.out.println("Correct Guess");
                System.out.println("The letter is:" + randomLetter);
                isGuessed = true;
            }

            else if (enteredLetter > randomLetter) {
                System.out.println("Incorrect Guess");
                System.out.println("The letter is too high");

            }

            else if (enteredLetter < randomLetter) {
                System.out.println(enteredLetter);
                System.out.println("Incorrect Guess");
                System.out.println("The letter is too low");


            }

            }
        }

    }
}

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