我是Android Studio新手,并且有一个我正在处理的计算器应用程序。现在,当我除以零时,我自然得到错误信息" Infinity",但如果我想改变它说,"不能除以零",我怎么会去吧?
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Divisionpage extends AppCompatActivity implements View.OnClickListener {
private Button btnDiv;
private TextView AnswDiv;
private EditText Divt1, Divt2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_divisionssida);
init();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private void init() {
btnDiv = (Button)findViewById(R.id.btnDiv);
AnswDiv = (TextView)findViewById(R.id.AnswDiv);
Divt1 = (EditText)findViewById(R.id.Divtal1);
Divt2 = (EditText)findViewById(R.id.Divtal2);
btnDiv.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String num7 = Divt1.getText().toString();
String num8 = Divt2.getText().toString();
switch (v.getId()){
case R.id.btnDiv:
try {
float division = Float.parseFloat(num7) / Float.parseFloat(num8);
AnswDiv.setText(String.valueOf(division));
}catch (Exception e) {
AnswDiv.setText("Could not divide!");
}
break;
}
}
}
我尝试捕获异常以显示错误消息,但您失败了。你有什么建议?
答案 0 :(得分:0)
嗯,你实际上可以检查num8值,如果它的0设置正确的消息。
@Override
public void onClick(View v) {
String num7 = Divt1.getText().toString();
String num8 = Divt2.getText().toString();
switch (v.getId()){
case R.id.btnDiv:
try {
final float denominator = Float.parseFloat(num8);
if(denominator == 0){
AnswDiv.setText("Can't divide by zero");
return;
}
float division = Float.parseFloat(num7) / Float.parseFloat(num8);
AnswDiv.setText(String.valueOf(division));
}catch (Exception e) {
AnswDiv.setText("Could not divide!");
}
break;
}
}
您可以进一步改善用户体验,改进异常处理,例如: 除非在edittext中受限制,否则用户可能会引入非数字字符。尝试解析所述字符将抛出NumberFormatException,它将在您的异常子句中捕获并设置消息。这可以改进,但通知用户只有数字字符有效。
catch (NumberFormatException ex){
AnswDiv.setText("Only numbers allowed!");
}