-1
試圖限制我的Android猜謎遊戲猜測的數目,但它與事實我想比較兩個整數時,其中一人已被轉換爲奮鬥一個字符串:
while (userGuess != userNumber && ++attempts < maxAttempts) ;
我不知道如何改變它。
順便說一下,我知道,因爲它代表着我的代碼將直接進入最終的if語句,每當我按下猜測按鈕時,它會說我已經嘗試了3次。
感謝
package lab.mad.cct.c3375331task1;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class Task1Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task1_layout);
final TextView textResponse = (TextView) findViewById(R.id.txtResponse);
final TextView guessText = (TextView) findViewById(R.id.txtAnswer);
final EditText userGuess = (EditText) findViewById(R.id.etNumber);
Button pressMe = (Button) findViewById(R.id.btnGuess);
// When the button is clicked, it shows the text assigned to the txtResponse TextView box
pressMe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String randText = "";
Random randGen = new Random();
int ranNum = randGen.nextInt(5);
int userNumber = Integer.parseInt(userGuess.getText().toString());
int attempts = 0;
final int maxAttempts = 3;
while (userGuess != userNumber && ++attempts < maxAttempts) ;
if (userNumber >19) {
guessText.setText("Please guess between 0 and 20");
} else if (userNumber == ranNum) {
guessText.setText("You did it!");
guessText.setBackgroundColor(Color.WHITE);
} else if (userNumber < ranNum) {
guessText.setText("Your answer is too low. Guess again!");
guessText.setBackgroundColor(Color.RED);
} else if (userNumber > ranNum) {
guessText.setText("Your answer is too high. Guess again!");
guessText.setBackgroundColor(Color.RED);
}
if (attempts == maxAttempts)
guessText.setText("You have guessed incorrectly three times. The answer was" + ranNum);
randText = Integer.toString(ranNum);
textResponse.setText("");
userGuess.setText("");
}
});
}
}
你得到了什麼確切的錯誤,你可以張貼錯誤跟蹤。 –
當然。它是:運算符'!='不能應用於'android.widget.EditText','int' –
您可以從EditText獲得String值,然後使用Integer.parseInt()與您的int值進行比較。 – algojava