我正在尝试创建一个用于计算考试笔记的应用程序 当我按下计算并且没有任何小数时,它会显示答案,但如果有小数则会崩溃
public class MainActivity extends AppCompatActivity {
TextView Result;
EditText Number1 , Number2, Number3, Number4, Number5, Number6;
Button Calculate;
float result_num;
int num1,num2,num3,num4,num5,num6;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Result = (TextView)findViewById(R.id.Result);
Number1 = (EditText)findViewById(R.id.Number1);
Number2 = (EditText)findViewById(R.id.Number2);
Number3 = (EditText)findViewById(R.id.Number3);
Number4 = (EditText)findViewById(R.id.Number4);
Number5 = (EditText)findViewById(R.id.Number5);
Number6 = (EditText)findViewById(R.id.Number6);
Calculate = (Button)findViewById(R.id.Calculate);
Calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
num1 = Integer.parseInt(Number1.getText().toString());
num2 = Integer.parseInt(Number2.getText().toString());
num3 = Integer.parseInt(Number3.getText().toString());
num4 = Integer.parseInt(Number4.getText().toString());
num5 = Integer.parseInt(Number5.getText().toString());
num6 = Integer.parseInt(Number6.getText().toString());
result_num = ((((num1 + num2 + num3 + num4) / 4) * 20) / 100) + ((((num5 + num6) / 2) * 80) / 100);
Result.setText(String.valueOf(result_num));
}
});
}
}
答案 0 :(得分:1)
基本上,您尝试将Double
或Float
值解析为Integer
类型,代码如下:
Integer.parseInt(Number1.getText().toString());
您的代码不适用于十进制值。但是您可以将其更改为Double值,如下所示:
double value1 = Double.parseDouble(Number1.getText().toString());
答案 1 :(得分:0)
使用Float而不是Integer。整数无法解析(并操作)带小数点的数字。
补充:这是错误检查代码:
try {
num1 = Double.parseDouble(Number1.getText().toString());
num2 = Double.parseDouble(Number2.getText().toString());
...
}
catch (NumberFormatException ex) {
Toast.makeText(this, "Error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}