简体   繁体   English

字母猜谜游戏中的“while循环” Java

[英]“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.我正在尝试制作字母猜谜游戏,其中用户需要猜测 A - Z 之间的字母,如果猜出的字母不正确,则表示该字母高于或低于猜测的字母。 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.这是带有此 Boolean 变量的更新代码,就像在提到的评论部分中一样。

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)但是您还必须考虑可能添加一个 try / catch / finally 块,然后在 finally 块部分关闭您的扫描仪(最终将始终被调用)

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.我也摆脱了这些控制循环,实际上使用 char 的一大好处是你可以将 ASCII 值与其他字符进行比较。

Here where we just comparing the characters in Uppercase we can directly compare these characters to each other with enteredLetter > randomLetter for example.这里我们只是比较大写的字符,我们可以直接比较这些字符,例如enteredLetter > randomLetter

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.此比较将检查 ASCII值 A=65 > D=69 SO A 不大于 D 和 go 到下一个条件。

Also you should check for valid input with Characters the way should be the static Method of class characterisLetter() .此外,您应该使用 Characters 检查有效输入,方式应该是 class 字符isLetter()的 static 方法。 Also don't take input as string instead take the input directly as character with char myLetter = scan.next().charAt(0);也不要将输入作为字符串,而是将输入直接作为字符使用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");


            }

            }
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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