Java EditText中的多个编号,并指定了编号
我试图得到用户输入的数字,并将其与指定值相乘。我看不出我犯了什么错误,我的应用程序一直在崩溃。我甚至不能运行它 MainActivity.javaJava EditText中的多个编号,并指定了编号,java,android,Java,Android,我试图得到用户输入的数字,并将其与指定值相乘。我看不出我犯了什么错误,我的应用程序一直在崩溃。我甚至不能运行它 MainActivity.java public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener { Button calculateBtn; EditText userEcts; TextView summary; int
public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener {
Button calculateBtn;
EditText userEcts;
TextView summary;
int price = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userEcts = (EditText) findViewById(R.id.ects_input);
summary = (TextView) findViewById(R.id.text_summary);
calculateBtn = (Button) findViewById(R.id.calculate);
calculateBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//When the button is clicked, call the calculate method.
calculate();
}
});
}
public void calculate() {
//gets entered text from the EditText,and convert to integers.
Double ects = Double.parseDouble(userEcts.getText().toString());
//do the calculation
Double calculatedPrice = ects * price;
//set the value to the TextView, to display on screen.
summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
}
}
您正在实现MSelectedListener
change OnItemSelectedListener to View.OnClickListener
您应该这样做:
summary.setText("Ukupno za platit: " + calculatedPrice + "kn");
String+Double=String我个人建议您在解析字符串之前,在calculate方法上进行如下检查,因为双精度字符串在解析时也会导致崩溃:
public void calculate() {
//Put this empty check to prevent crash while parsing empty string.
if (!TextUtils.isEmpty(userEcts.getText.toString())){
Double ects = Double.parseDouble(userEcts.getText().toString());
//do the calculation
Double calculatedPrice = ects * price;
//set the value to the TextView, to display on screen.
summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
}
}
希望这有帮助。它现在可以工作了。。。在现有代码上,我添加了此代码
@Override
public void onClick(View v) {
calculate();
}
无论如何,谢谢:)请添加错误日志错误是什么?您可以包括您的崩溃日志吗?图片如下:我已经按照您的回答完成了所有操作,但应用程序仍然会在运行应用程序时崩溃。。。以下是catlog的图片: