简体   繁体   English

如何读取空格之间的整数?

[英]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.我正在尝试编写一个 Hangman 游戏项目,其中用户可以有 15 个猜测和 4 个空格来检查。 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 .现在您有一个存储在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.此外,您的 for 循环似乎正在检查用户输入的字母是否在秘密单词中。 No need to use a for loop for this!无需为此使用 for 循环! Just do this:只需这样做:

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

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

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