Hello guys, here is my tutorial on how to do a simple calculator in Java.
in this tutorial i assume that you already have a Jcreator pro a the JDK.
How to get those item(It was mentioned in my first Java Tutorial the Basic Hello world.)
Ok let's start.
First and foremost i'm gonna show you how to do simple addition in Java.
We'll gonna our file "MySimpleCalculator".
First thing we need to do is to access the object called Scanner by importing the Library called java.util.Scanner, because we will let the user to input two numbers.
And of course in calculator, we all know that in a basic calculator there were 4 operations. Those were Addition, Subtraction, Multiplication, and Division.
//-----------------------------------------------
import java.util.Scanner;
public class MySimpleCalculator
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
int ChooseOperation = 0, num1 = 0, num2 = 0;
System.out.print("Please choose operation \n[1] Addition\n[2] Subtraction\n[3] Multiplication\n[4] Division\nEnter your Choice: ");
ChooseOperation = input.nextInt();
if(ChooseOperation == 1)
{
System.out.print("Enter number 1: ");
num1 = input.nextInt();
System.out.print("Enter number 2: ");
num2 = input.nextInt();
System.out.print("The Sum is " + (num1 + num2));
}
else if(ChooseOperation == 2)
{
System.out.print("Enter number 1: ");
num1 = input.nextInt();
System.out.print("Enter number 2: ");
num2 = input.nextInt();
System.out.print("The Difference is " + (num1 - num2));
}
else if(ChooseOperation == 3)
{
System.out.print("Enter number 1: ");
num1 = input.nextInt();
System.out.print("Enter number 2: ");
num2 = input.nextInt();
System.out.print("The Product is " + (num1 * num2));
}
else if(ChooseOperation == 4)
{
System.out.print("Enter number 1: ");
num1 = input.nextInt();
System.out.print("Enter number 2: ");
num2 = input.nextInt();
System.out.print("The Quotient is " + (num1 / num2));
}
else
{
System.out.print("Invalid Choice!");
}
}
}
//------------------------------------------
The output would be:
Please choose operation
[1] Addition
[2] Subtraction
[3] Multiplication
[4] Division
Enter your Choice: 1
Enter number 1: 10
Enter number 2: 10
The Sum is 20
//------------------------------------------
Ok.. That's it for this time..
Hope this would help you..
thanks...
No comments:
Post a Comment