簡體   English   中英

更改數組列表中的值?

[英]Changing the value inside an Array List?

for(int i = 0; i <= gameWord.length()-1; i++)
    {
        if(guessLetter.charAt(0) == (gameWord.charAt(i)))
        {
            hideword[i] = guessLetter.charAt(0);
        }
        else if(guessLetter.charAt(0) != (gameWord.charAt(i)))
        {
            System.out.print("_" + " ");
        }
    }

我正在制作一個hang子手游戲,並且創建了一個名為hideword的數組列表。 Hideword為用於游戲的單詞中的每個字母打印一個下划線。 我正在嘗試糾正一種方法,該方法將下划線替換為用戶猜測的字母。 但是這段代碼

hideword[i] = guessLetter.charAt(0);

不起作用 它給我“需要數組,但是找到了java.util.ArrayList

有人幫忙嗎?

然后,hideword必須是一個arraylist。 使用hideword.set(index, character)進行賦值,而不是像數組一樣訪問它。

ArrayList不是數組,而是List實現(但是,其實現由數組支持 -因此有名稱)。

hideword聲明為char數組:

private char[] hideword;

並在使用前對其進行初始化:

hideword = new char[gameword.length];

您的代碼無需改變其基本意圖,就可以大大簡化:

  • 無需從長度中減去1 ,只需更改比較運算符
  • 有沒有需要有你ifelse -我們已經知道這是不是相等的,因為我們是在else
  • 而不是無用的打印,而是將下划線分配給陣列插槽
  • 最后打印一張

像這樣:

for (int i = 0; i < gameWord.length(); i++) {
    if (guessLetter.charAt(0) == (gameWord.charAt(i))) {
        hideword[i] = guessLetter.charAt(0);
    } else {
        hideword[i] = '_';
    }
}
// print hideword

如果hideword不存在,那么您的代碼將更加簡單,而只需在測試每個字符時簡單地System.out.print()即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM