Reputation: 11
I'm implementing a simple adder application. When I click the sum without entering any numbers the application crashes. Why? I defined the function such that when either num1
or num2
is empty it should print "Invalid---"
. Why is it crashing then?
When i click the sum without entering any number it crashes .Why? As i already defined function when either entry among num1 or num2 is empty it should print "Invalid---" .
My java code for MainActivity
is here:
import ...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v){
EditText a = (EditText)findViewById(R.id.etNum1);
EditText b = (EditText)findViewById(R.id.etNum2);
TextView c =(TextView)findViewById(R.id.tvResult);
String x=a.getText().toString();
String y=b.getText().toString();
if( (x!="" && y!="")) {
int num1 = Integer.parseInt(x);
int num2 = Integer.parseInt(y);
int num3 = num1 + num2;
c.setText("Good entry");
}
else{
c.setText("Invalid num1 or num2");
}
}
Upvotes: 0
Views: 260
Reputation: 941
Can you please try using this --
if((!"".equals(x)) && (!"".equals(y))) {
int num1 = Integer.parseInt(x);
int num2 = Integer.parseInt(y);
int num3 = num1 + num2;
c.setText("Good entry");
}
Upvotes: 1