Reputation: 65
So I'm creating a basic calculator for class using java that will ask the user for 2 numbers then will ask them what sort of calculation they want. It works but not as I wanted and i'm out of patience trying to figure out these methods. Just started learning them by the way.
Ok so, what i need held with is i would like to tell the user that its bad math to divide by 0 and that he will need to change his numbers. But how do I get the prompt to come back up if he inputs a 0 as one of the numbers?
for example, here is a snippet of my code for division:
public static float divide(float num1, float num2){
if ((num1 == 0) || (num2 == 0)){
JOptionPane.showMessageDialog(null, "numbers cannot be divisible by 0");
//I would like to give the user an option here to change his numbers to something else.
return 0;}
else
return num1 / num2;
please help.
package assignment4_main;
import javax.swing.JOptionPane;
public class Assignment4_Main {
public static void main(String[] args) {
float result;
float num1 = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter first number: ", "Calculator" , JOptionPane.QUESTION_MESSAGE));
float num2 = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter second number: ", "Calculator", JOptionPane.QUESTION_MESSAGE));
int userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "What would you like to do with these numbers?\n" + "1- Add 2- Subtract 3- Multiply 4- Divide 5- Quit", "Calculator", JOptionPane.QUESTION_MESSAGE));
switch(userInput){
case 1:
{result = add(num1, num2);
JOptionPane.showMessageDialog(null, "Addition = " + result);
break;}
case 2:
{result = subtract(num1, num2);
JOptionPane.showMessageDialog(null, "Subtraction = " + result);
break;}
case 3:
{result = multiply(num1, num2);
JOptionPane.showMessageDialog(null, "Multiplication = " + result);
break;}
case 4:
{result = divide(num1, num2);
JOptionPane.showMessageDialog(null, "Division = " + result);
break;}
case 5:
break;
}
}
public static float add(float num1, float num2){
return num1 + num2;
}
public static float subtract(float num1, float num2){
return num1 - num2;
}
public static float multiply(float num1, float num2){
return num1 * num2;
}
public static float divide(float num1, float num2){
if ((num1 == 0) || (num2 == 0)){
JOptionPane.showMessageDialog(null, "numbers cannot be divisible by 0");
return 0;}
else
return num1 / num2;
}
}
Upvotes: 0
Views: 718
Reputation: 8718
There are more elegant solutions to this of course, but this one should get you on the way:
public static void main(String[] args) {
int number;
while (true) {
Object[] message = {"Input some number that is not 0: "};
String numberString = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION);
try {
number = Integer.parseInt(numberString);
} catch (NumberFormatException e) {
continue;
}
if (number != 0) {
break;
}
}
System.out.println(number);
}
Upvotes: 1