Java Tutorial
Java Project: Calculator
A four-function calculator with methods per operator and a check for divide-by-zero.
What you will build
This project is a four-function calculator: add, subtract, multiply, and divide. Each operator lives in its own method. Division checks the divisor before it runs. The examples use hardcoded numbers so they compile at once. Click Try it in Java to open /java/try.
One method per operator
Each operator takes two double values and returns a double. Using double keeps 10 divided by 4 as 2.5, not 2.
Example
public class Main {
static double add(double a, double b) { return a + b; }
static double subtract(double a, double b) { return a - b; }
public static void main(String[] args) {
System.out.println(add(10.0, 4.0));
System.out.println(subtract(10.0, 4.0));
}
}Guard divide-by-zero
Return a boolean for success and print a message when the divisor is zero.
Example
public class Main {
static boolean divide(double a, double b, double[] out) {
if (b == 0.0) return false;
out[0] = a / b;
return true;
}
public static void main(String[] args) {
double[] q = {0};
if (divide(10.0, 4.0, q)) System.out.println("10 / 4 = " + q[0]);
else System.out.println("Cannot divide by zero");
if (divide(10.0, 0.0, q)) System.out.println("10 / 0 = " + q[0]);
else System.out.println("Cannot divide by zero");
}
}Complete calculator
Pick an operator with a char and an if / else if chain. Unknown operators get their own message.
Example
public class Main {
static double add(double a, double b) { return a + b; }
static double subtract(double a, double b) { return a - b; }
static double multiply(double a, double b) { return a * b; }
static void apply(double a, char op, double b) {
if (op == '+') System.out.println(a + " + " + b + " = " + add(a, b));
else if (op == '-') System.out.println(a + " - " + b + " = " + subtract(a, b));
else if (op == '*') System.out.println(a + " * " + b + " = " + multiply(a, b));
else if (op == '/') {
if (b == 0) System.out.println("Cannot divide by zero");
else System.out.println(a + " / " + b + " = " + (a / b));
} else System.out.println("Unknown operator");
}
public static void main(String[] args) {
apply(10, '+', 4);
apply(10, '-', 4);
apply(10, '*', 4);
apply(10, '/', 4);
apply(10, '/', 0);
}
}Practice
- Compile the complete program at
/java/try. - Change one input value and compile again.
- Replace a hardcoded number with
Scannerwhen you want typed input.