[英]What's wrong with this randomized string and if-statement in java
我在用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);
}
}
您应该只生成一次该单词,然后执行检查并输出:
while (i < 9) {
String exampleWord = exampleWord();
if ("cat".equals(exampleWord) || "dog".equals(exampleWord)){
System.out.println(exampleWord);
i++;
}
}
是的,你是对的。 每次调用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++;
}
}
}
另外,似乎您在exampleWord
方法中不必要地进行了一些工作。 你可以做
public static String exampleWord() {
String[] listedWords = {"cat", "dog", "horse", "fish", "turtle", "mouse"};
Random random = new Random();
return listedWords[random.nextInt(listedWords.length)];
}
问题是,每次将“ cat”或“ dog”与结果进行比较时,您都在执行exampleWord(),然后再次执行它以打印结果。 只需在循环内执行exampleWord()一次,将其存储在变量中,最后比较并打印结果即可。 就像是:
String result = exampleWord()
if("cat".equals(result) || "dog".equals(result)) {
System.out.println(result);
i++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.