Introduction
In this tutorial we gonna learn ho w to make a calculator that take user input
and allow mathematical operation on it,like sum, substraction, multiplication,
division.
Explanation of program
So, let understand how we gonna do that,we basically use if else
statement in this program.we firstly declare some variables for storing two
value and one more two store output .Since for user to perform function again
and again we gave him a option of retry .
We will use do while loop also here,we put all that in do while loop, so
that when ever user give particular instruction program will re excute . This
will be more clear when you see the program.
After that we out a msg on scree two enter two number and since we declare two
variables above we store that in it and next we display a small menu to user
so as to choose which matamaetical operation he/she want to perform.
And we recive the input using another variable.
Then we will have five if else statements,four will be for operator and
another one for the default message,in case user input some another option
that doesn't exist.
All first four if else statement will be same ,just a change in operator ,as
you can see below.
Q) Calculator using if else statement in Java.
Sol.)
import java.util.Scanner;
public class Calc{
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
float a,b,z;
String retry;
int operator;
do{
System.out.printf("Enter two numbers two perform operation" +"\n");
a= in.nextInt();
b=in.nextInt();
System.out.println("1. addition");
System.out.println("2. subtratcion");
System.out.println("3. division");
System.out.println("4. multiplication");
System.out.println("choose your operator:");
operator =in.nextInt();
if (operator==1)
{z=a+b;
System.out.printf("\n" + "Sum=" +z);
}
else if (operator==2)
{z=a-b;
System.out.printf("\n" +"Diffrence="+z);
}
else if (operator==3)
{z=a/b;
System.out.printf("\n" +"Division="+z);
}
else if (operator==4)
{ z= a*b;
System.out.printf("\n" + "Multiplication=" + z);
}
else
{
System.out.printf("\n" + "not an option");
}
System.out.printf("\n" +"press y to retry use it and n to exit");
retry =in.nextLine();
} while(retry=="y" && retry!="n");
}
}
Output:
Enter two numbers two perform operation
4
5
1. addition
2. subtratcion
3. division
4. multiplication
choose your operator:
1
Sum=9.0
press y to retry use it and n to exit
Some more questions like this you can find out on our website to check more questions for practice
Click the bold letters
enjoy the coding with Bigfootcode
0 Comments
if you have any doubt let me know in comment