我是android的新手。单击此按钮后(当TextView中没有任何内容,即它显示“”)我得到NumberFormatException但在其他情况下它正在工作。我想显示Toast消息,如果String中没有任何内容,我的TextView最初是
android:id="@+id/text_view_result"
android:text=""
该按钮是
buttonExpense.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Integer.valueOf(result) < 0) {
Toast.makeText(getActivity().getApplicationContext(), "Amount can't be negative", Toast.LENGTH_SHORT).show();
return;
}
else if (Integer.valueOf(result) > 0) {
Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra("result", result);
startActivity(intent);
}
else if(Integer.valueOf(result) == 0) {
Toast.makeText(getActivity().getApplicationContext(), "Amount can't be 0", Toast.LENGTH_SHORT).show();
return;
}
else{
Toast.makeText(getActivity().getApplicationContext(), "Please enter your amount", Toast.LENGTH_SHORT).show();
return;
}
}
});
使用结果String的方法在下面给出的方法中
private void onEqualButtonClicked() {
int res = 0;
try {
int number = Integer.valueOf(tmp);
int number2 = Integer.valueOf(resultTextView.getText().toString());
switch (operator) {
case "+":
res = number + number2;
break;
case "/":
res = number / number2;
break;
case "-":
res = number - number2;
break;
case "X":
res = number * number2;
break;
}
result = String.valueOf(res);
resultTextView.setText(result);
}
catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:0)
空字符串不是数字。你想要做的是先检查它是否是一个数字,然后再处理它。
int number;
try {
number = Integer.parseInt(result);
} catch (NumberFormatException exception) {
// handle case where it's not a number
}
// perform logic where it is a number