简体   繁体   中英

How to read integers between white spaces?

I'm trying to write a Hangman game project in which the user can have 15 guesses and 4 spaces to check. The numbers (of spaces) are separated by spaces. Here is my code, but it doesn't work for some reasons. Any help is appreciated !

System.out.println("\nPlease enter the letter you want to guess: ");
        char guessLetter = input.next().charAt(0);

        if (Character.isLetter(guessLetter)){
            System.out.println("Please enter the spaces you want to check (separated by spaces): ");
            String guessSpaces = input.next();


            for (int index = 0; guessSpaces.charAt(index) == ' ';index++){
                if(guessSpaces.charAt(index)== secretWord.indexOf(guessLetter)){
                    System.out.println("You guess is in the word");

I don't really understand your code, but if you want to read some integers, this is how to do it:

String[] strings = input.nextLine().split(" ");
ArrayList<Integer> integers = new ArrayList<>();
for (String s : strings) {
    if (s.trim().equals("")) {
        continue;
    }
    integers.add(Integer.parseInt(s));
}

Now you have a list of integers stored in integers . For example, if I enter

90 68 6 786

The array list will contain exactly that. However, if you enter some invalid values in there, an exception will be thrown.

Also, it seems like that your for loop is checking whether the letter that the user entered is in the secret word. No need to use a for loop for this! Just do this:

if (secretWord.contains(Character.toString(guessLetter))) {
    System.out.println("Your guess is in the word!");
}

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