我尝试创建一个输入2个数字并显示其总和的加法应用程序。该应用给出了错误的答案。
public class MainActivity extends AppCompatActivity {
EditText edtTxt1;
EditText edtTxt2;
TextView txt;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.add_button);
edtTxt1 = (EditText)findViewById(R.id.editText1);
edtTxt2 = (EditText)findViewById(R.id.editText2);
txt = (TextView)findViewById(R.id.answer_textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(edtTxt1.getText().toString());
int num2 = Integer.parseInt(edtTxt1.getText().toString());
int result = num1 + num2;
txt.setText(""+result);
}
});
}
}
答案 0 :(得分:2)
您正在从同一编辑文本中获得两个变量的输入数字,请像下面这样进行更新
int num1 = Integer.parseInt(edtTxt1.getText().toString());
int num2 = Integer.parseInt(edtTxt2.getText().toString());
答案 1 :(得分:1)
'在您的按钮中单击,您将从类似的编辑文本中获得展位号,
int num1 = Integer.parseInt(edtTxt1.getText().toString());
int num2 = Integer.parseInt(edtTxt1.getText().toString());
“正确” “希望您能找到解决方案”
答案 2 :(得分:0)
这是解决方法
public class MainActivity extends AppCompatActivity {
EditText edtTxt1;
EditText edtTxt2;
TextView txt;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.add_button);
edtTxt1 = (EditText)findViewById(R.id.editText1);
edtTxt2 = (EditText)findViewById(R.id.editText2);
txt = (TextView)findViewById(R.id.answer_textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(edtTxt1.getText().toString());
int num2 = Integer.parseInt(edtTxt2.getText().toString());
int result = num1 + num2;
txt.setText(""+result);
}
});
}
}
我希望这能解决您的问题。让我知道是否有事。