public class MainActivity extends AppCompatActivity {

    int randomNumber;

    public void guess(View view)
    {
        EditText numberEntered = (EditText) findViewById(R.id.enteredNumber);
        String numberEnteredString = numberEntered.getText().toString();
        int numberEnteredInteger = Integer.parseInt(numberEnteredString);

        String message = "";
        if (numberEnteredInteger == randomNumber ) {
            message = "Correct Guess";
        }
        else if(numberEnteredInteger < randomNumber) {
            message = "Too Low!";
        }
        else if (numberEnteredInteger > randomNumber){
            message = "Too High!";
        }
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }


我是Java,ANDROID STUDIO的初学者。我的任务是要求用户输入一个与我的随机数匹配的数字。如果用户输入的数字与我的随机数匹配,则应显示示例代码中提到的消息。

以下代码针对if语句中提到的所有三种情况运行。在“号码”字段中未输入任何号码时,如何编写用于显示消息的代码?

最佳答案

尝试这个

boolean error = false;
String message = "";
int numberEnteredInteger;
try {  numberEnteredInteger = Integer.parseInt(numberEnteredString);
}
Catch (NumberFormatException e) {
   error = true;
}
if (error) {
    message = "Invalid Number"
}
else if (numberEnteredInteger == randomNumber ) {


...

10-04 18:59