简体   繁体   English

如何在Java上创建随机字母猜游戏

[英]How to create a random letter guessing game on java

I am trying to create a guessing game on java. 我正在尝试在Java上创建一个猜谜游戏。 The user is to guess a letter of the alphabet that the computer has already generated. 用户将猜测计算机已经生成的字母。 Lowercase and uppercase letters should be included, but the guess "A" is equivalent to the guess "a". 应包括小写和大写字母,但是猜测“ A”等同于猜测“ a”。 I am trying to create a loop that repeatedly asks for a letter until the user guesses the computer's letter. 我正在尝试创建一个反复询问字母的循环,直到用户猜出计算机的字母为止。 After each incorrect guess, I need to tell the user whether their letter came before or after the correct letter. 在每次错误的猜测之后,我需要告诉用户他们的字母是在正确的字母之前还是之后。

I can not figure out how use the Random class with both uppercase and lowercase letters. 我不知道如何将Random类同时使用大写和小写字母。 I can't figure out how to convert it to numbers to tell if the guess is before or after. 我不知道如何将其转换为数字以判断猜测是在之前还是之后。

import java.util.Random;
import java.util.Scanner;

public class GuessLetter {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
Random ran = new Random();

String alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

int N= alphabet.length();

char a =(alphabet.charAt(ran.nextInt(N)));

Scanner scanner=new Scanner(System.in);

System.out.println("Enter a letter:");

String i= scanner.nextLine();

char b =(i.charAt(0));

while  {

You can use String.indexOf(char) to find the position of the user's input in your set of possible characters. 您可以使用String.indexOf(char)在可能的字符集中查找用户输入的位置。 Then compare that position to the random number you generated to determine if it's higher or lower. 然后将该位置与您生成的随机数进行比较,以确定它的高低。

I can't figure out how to convert it to numbers to tell if the guess is before or after. 我不知道如何将其转换为数字以判断猜测是在之前还是之后。

Try using a Map to know the position of each character: 尝试使用Map来了解每个字符的位置:

public static final String lowerCase = "abcdefghijklmnopqrstuvwxyz";
public static final String upperCase = lowerCase.toUpperCase();
public static final Map<Character, Integer> charMap = new HashMap<>();

static {
    for (Character c : lowerCase) {
        charMap.put(c, lowerCase.indexOf(c));
    }

    for (Character c : upperCase) {
        charMap.put(c, upperCase.indexOf(c));
    }
}

I can not figure out how use the Random class with both uppercase and lowercase letters 我不知道如何将Random类同时使用大写和小写字母

With the above setup, you simply have to get a random character from upperCase or lowerCase and find the position of that character in the map. 通过上述设置,您只需要从upperCaselowerCase获取随机字符, upperCase在地图上找到该字符的位置。

public static final String allCharacters = lowerCase + upperCase;
public static final Random rand = new Random();

static {
    char randomChar = allCharacters.charAt(rand.nextInt(allCharacters.size()));
    int position = charMap.get(randomChar);
}

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

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