This Java tutorial will tell you how to write a calculator program in Java, who would further help you to add, subtract, multiply or divide any number conveniently in quick time.
How to Write a Calculator Program in Java?
In this Java Tutorial you will learn how to write a Calculator program in Java in easy steps. Calculator program in Java is often used by the developers for calculations like addition, subtraction, multiplication or division.
In this example of writing program in Java for a Calculator, we have used a class 'calculator'.
System.in takes the input from the system/user at run time. InputStreamReader reads the input from System.in and then keep it into Buffer.
parseInt method of Integer class has been used in order to convert the strings into integers. If a user enters for a "+" operator, the method would add two integer numbers and display the output accordingly. Now, if the user opts for a "-" operator, the method will subtract both the numbers. However, the first number entered is bigger than the second number, the output will show a positive value else it would display a negative value.
Similarly, if you choose for a "*" operator, the result will be shown as the multiplication of both the numbers, while entering a "/" will divide the two numbers. However, if the first number entered is bigger than the second entered number, the final result will be an integer or else fraction.
Example of Calculator program in Java
package Tutorial; import java.io.*; class calculator { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); double x, y, store = 0; char cal; System.out.println("Enter the two numbers: "); x = Integer.parseInt(reader.readLine()); y = Integer.parseInt(reader.readLine()); System.out.println("Enter the operator: "); cal = (char) System.in.read(); if (cal == '+') { store = x + y; } else if (cal == '-') { if (x > y) store = x - y; if(x < y) store= x - y; } else if (cal == '*') { store = x * y; } else if (cal == '/') { if (x > y) store = x / y; if( x < y) store = x / y; } else System.out.println("Wrong operator: "); System.out.println("The result is: " + store); } }
Output:
Enter the two numbers:
12
10
Enter the operator:
*
The result is: 120
Enter the two numbers:
12
14
Enter the operator:
-
The result is: -2.0
Enter the two numbers:
12
6
Enter the operator:
/
The result is: 2.0
Enter the two numbers:
20
20
Enter the operator:
+
The result is: 40.0