0

こんにちは、私はプログラミングが初めてで、絞首刑執行人ゲームを作成する割り当てがあります。今私が抱えている問題は推測です。プログラムはすべてを正しく推測しており、正しく動作しています。の文字を印刷しないJTextFieldか、1文字だけ印刷しますが、もう一度正しいと思うと、前の文字が上書きされます。

では、助けの手を差し伸べてくれるフレンドリーな魂はいますか?

チェック用のコードは次のとおりです。

  private class check implements ActionListener {
    public void actionPerformed(ActionEvent ae) {
        try {  
            // Grabs the letter from the guessField and converts it into a char which can be used to compare against the word.
         guess = guessField.getText();

        guessField.setText("");
        char guess2 = guess.charAt(0);


        String displaySecret = "";

        for (int i = 0; i < random.length(); i++)
            displaySecret += "*";


        //read in a guess
        int position = random.indexOf(guess2);
        //now position contains the index of guess inside secret, or
        //-1 if the guess was wrong

        String newDisplaySecret = "";
        for (int i = 0; i < random.length(); i++)
            if (i == position)
                newDisplaySecret += random.charAt(i); //newly guessed character
            else
                newDisplaySecret += displaySecret.charAt(i); //old state

        displaySecret = new String(newDisplaySecret);

        wordField.setText(displaySecret);

}

4

2 に答える 2

0

ディスプレイシークレットを初期化する方法を変更する必要があります

String displaySecret = "";
    for (int i = 0; i < random.length(); i++)
        displaySecret += "*";

String displaySecret = wordField.getText();
if(displaySecret=NULL){/*case for fist execution*/
    displaySecret="";
    for (int i = 0; i < random.length(); i++)
    displaySecret += "*";
}

これにより、ある推測から別の推測への最後のエントリを記憶することができます。Label が正しく初期化されている場合は、if ステートメント全体を削除できます。

ただし、確率変数に同じ文字が複数回出現する場合、最初の文字しか見つからないという別の問題があります。

条件:

if(i=position)

する必要があります

if (guess2 == random.charAt(i))
于 2013-10-17T12:45:53.710 に答える
0
wordField.setText(displaySecret);

wordField.setText(wordField.getText()+displaySecret);

world フィールド内のコードが値を新しいものに置き換えると考えてください。メソッド宣言はそれsetを示していますが、そうではありませんaddText

于 2013-10-17T12:04:35.850 に答える