-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