gpt4 book ai didi

java - 当 EditText 为空时防止 nullPointerException

转载 作者:行者123 更新时间:2023-12-02 10:26:33 25 4
gpt4 key购买 nike

您好,我正在制作一个应用程序来计算来自 EditTexts 的用户输入的平均值。当我运行该应用程序时,它可以工作,但是当我将字段留空时,它会抛出 nullPointerException。我知道这是什么以及一般如何解决它们。在我的代码中,我正在考虑使用 if 语句来检查它是否为空。但我不知道如何检查整数的空/空值。有人可以解释一下检查这个的最佳方法/实践是什么吗?

欢迎任何提示等!

我的代码:

final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
public void onClick(View v) { TextView averageView = findViewById(R.id.averageView);

int grade[] = {Integer.parseInt(((EditText) findViewById(R.id.grade1)).getText().toString());
int weight[] = {Integer.parseInt(((EditText) findViewById(R.id.weight1)).getText().toString());

int weightTotal = weight[0];

int sum = grade[0] * weight[0];

int average = sum / weightTotal

String averageText = getString(R.string.average);
averageView.setText(averageText + Integer.toString(average));

最佳答案

这就是为什么您应该避免执行大量内联代码。

不存在空整数,需要从编辑文本中检查字符串

String value = ((EditText) findViewById(R.id.grade1)).getText().toString();
if(value != null && value.length() > 0){
try{
//Since edit text gives you a string you cannot guarantee you have a number input
int numberValue = Integer.parseInt(value);
catch(NumberFormatException e){
//handle exception
}
}

关于java - 当 EditText 为空时防止 nullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53914988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com