[英]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.