为什么我的.isEmpty在此代码中不起作用?

时间:2019-11-01 18:12:32

标签: java android

我要编写一个检查程序,以便用户在按下按钮之前写下一个要检查的数字。

public class MainActivity extends AppCompatActivity {
    int randomNumber;

    public void makeToast(String string) {
        Toast.makeText(MainActivity.this, string, Toast.LENGTH_LONG).show();
    }

    public void guess (View view) {
        final EditText showNumber = findViewById(R.id.showNumberEditText);

        int guessInt = Integer.parseInt(showNumber.getText().toString());

        if (showNumber.getText().toString().isEmpty()) {
            makeToast("Pleas Enter a Number!");
        } else if(guessInt > randomNumber) {
            makeToast("Lower");
        } else if (guessInt < randomNumber) {
            makeToast("Higher");
        } else {
            makeToast("Correct! Try Again!");

            Random random = new Random();
            randomNumber = random.nextInt(20) + 1;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Random random = new Random();
        randomNumber = random.nextInt(20) + 1;
    }
}

1 个答案:

答案 0 :(得分:0)

您必须考虑EditText可能尚未设置任何值,因此本质上可能包含 Null ,因此 .toString()。isEmpty()可能会失败带有 NullPointerException 。另外,如果它具有文本,则还需要考虑它甚至可能不是数字,因此需要将其转换为整数。而且字符串不能直接与整数进行比较,因此必须进行这种整数转换。

尝试下一个代码:

public void guess (View view) {
final EditText showNumber = findViewById(R.id.showNumberEditText);

Integer guessInt = convertToInteger(showNumber.getText());

if (guessInt == null) {
    makeToast("Pleas Enter a Number!");
 }else if(guessInt > randomNumber) {
        makeToast("Lower");
    } else if (guessInt < randomNumber) {
        makeToast("Higher");
    } else {
        makeToast("Correct! Try Again!");
        Random random = new Random();
        randomNumber = random.nextInt(20) + 1;
    }
}

public static Integer convertToInteger(final Editable source) {
    if (source != null) {
        try {
            final String text = source.toString();
            return Integer.parseInt(text);
        }
        catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
    }

    return null;
}