Java Android Studio:没有输入数字时应用程序崩溃
当我输入数字时,该按钮工作正常,但当我不输入数字时,它会崩溃。为了解决这个问题,我尝试使用一个条件语句,以便在没有输入数字的情况下,calculate按钮不会运行,但它仍然不起作用。我放了一条else线看看它是否打印了什么,但还是什么也没有Java Android Studio:没有输入数字时应用程序崩溃,java,android,input,crash,Java,Android,Input,Crash,当我输入数字时,该按钮工作正常,但当我不输入数字时,它会崩溃。为了解决这个问题,我尝试使用一个条件语句,以便在没有输入数字的情况下,calculate按钮不会运行,但它仍然不起作用。我放了一条else线看看它是否打印了什么,但还是什么也没有 public void onClick(View view) { //This is where I tried to fix it if (percentageText.getText()!=
public void onClick(View view) {
//This is where I tried to fix it
if (percentageText.getText()!=null && numberText.getText()!=null){
float percentage = Float.parseFloat(percentageText.getText().toString());
float dec = percentage / 100;
float total = dec * Float.parseFloat(numberText.getText().toString());
totalTextView.setText(Float.toString(total));
Log.d("myTag","Success!");
} else {
Log.d("myTag","Error no integer found");
}
}
下面是日志:
但是,如果我解析float,这应该无关紧要,因为if语句会阻止代码运行,对吗?或者它是否尝试以任何方式运行?要强制在edittext中输入数字,可以将此属性设置为edittext:
android:inputType="number"
尝试将另一个条件检查与空条件检查一起添加
(numberText.getText().toString().trim().getlength > 0 ) or (! numberText.getText().toString().trim().equalignourcase(""))
将此应用于percentage edittext和numbertext edittext是否尝试使用
try catch
将其包围?是否可以在此处发布logcat错误?您正在解析到float
这可能是问题所在。有关详细信息,请显示日志猫。请尝试在空条件检查的同时添加另一个条件检查。(numberText.getText().toString().trim().getlength>0)或(!numberText.getText().toString().trim().EqualingSource(“”)将此应用于百分比edittext和numberTextedittext@v-v您的解决方案有效,谢谢!