这个随机字符串和java中的if语句出了什么问题

0 java if-statement

我在java中弄湿了脚,我偶然发现了一个问题.我怀疑可能已经有了它的答案,但我太知道我应该寻找的是什么 - 这也意味着我的术语可能不正确.

在下面的代码中,我试图从一个单词数组中创建一个随机选择,然后使用if语句显示或不显示单词.问题是,虽然满足if语句的条件(获得字符串"cat"或字符串"dog"),但操作显示任何列出的单词,而不是"cat"或"dog"

我怀疑当我System.out.println(exampleWord());在第10行使用时,例程从数组中获取一个新值,实际上忽略了if语句.

最简单的方法是什么?

import java.util.Random; 

public class Phrasing {
    String word;

    public static void main(String[] args) {
        int i = 1;
        while (i < 9) {
            if ("cat".equals(exampleWord()) || "dog".equals(exampleWord())) {
                System.out.println(exampleWord()); 
                i++;
            }
        }
    }

    public static String exampleWord() {
        String[] listedWords = {"cat", "dog", "horse", "fish", "turtle", "mouse"};
        Random random = new Random();
        int index = random.nextInt(listedWords.length);
        Phrasing wordOutput;
        wordOutput = new Phrasing();
        wordOutput.word = listedWords[index];
        return (wordOutput.word);
    }
}
Run Code Online (Sandbox Code Playgroud)

Bog*_*kyi 6

您应该只生成一次单词然后执行检查并输出它:

while (i < 9) {
    String exampleWord = exampleWord();
    if ("cat".equals(exampleWord) || "dog".equals(exampleWord)){
        System.out.println(exampleWord); 
        i++;
    }
}
Run Code Online (Sandbox Code Playgroud)


Ima*_*kin 6

是的,你是对的.每次拨打电话时exampleWord(),都会生成一个随机字.尝试将其存储在String一次.

public static void main(String[] args) {
    int i = 1;
    while (i < 9) {
        String s = exampleWord();
        if ("cat".equals(s) || "dog".equals(s)) {
            System.out.println(s); 
            i++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,在exampleWord方法中,您似乎正在做一些不必要的工作.你可以做到

public static String exampleWord() {
    String[] listedWords = {"cat", "dog", "horse", "fish", "turtle", "mouse"};
    Random random = new Random();
    return listedWords[random.nextInt(listedWords.length)];
}
Run Code Online (Sandbox Code Playgroud)