In: Computer Science
Android Studio (Java)
I'm trying to create a simple calculator. I want to put out a message if they try to divide by 0.
I have this so far. What code should I put?
divide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (number1.getText().length() != 0 && number2.getText().length() != 0) { double n1= Double.parseDouble(number1.getText().toString()); double n2= Double.parseDouble(number2.getText().toString()); double res= n1 / n2; result.setText(String.valueOf(res)); } else { Toast.makeText(view.getContext(), "Please enter the numbers properly", Toast.LENGTH_SHORT).show(); } } });
Thanks for the question! Before doing the division n1 by n2, we need to ensure n2 is not equal to zero. We need to provide a checking just before we do that division, below is the updated code as how you need to do the checking. Please update the error message accordingly. ============================================================================================= divide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (number1.getText().length() != 0 && number2.getText().length() != 0) { double n1= Double.parseDouble(number1.getText().toString()); double n2= Double.parseDouble(number2.getText().toString()); // validate the denominator n2 is not zero before doing the division if(n2!=0){ double res= n1 / n2; result.setText(String.valueOf(res)); } else { Toast.makeText(view.getContext(), "ERROR. INVALID OPERATION. DIVISION BY /0", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(view.getContext(), "Please enter the numbers properly", Toast.LENGTH_SHORT).show(); } } });