简体   繁体   中英

How to create a random letter guessing game on java

I am trying to create a guessing game on 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". 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. 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. 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:

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

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.

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);
}

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