Calculator - if Learn programming Java

Lesson:

Basic Data Types


Exercise:

Calculator - if 21


Objetive:

Write a java program which asks the user for two numbers and an operation to perform on them (+,-,*,x,/) and displays the result of that operation, as in this example:

Enter first number: 5
Enter operation: +
Enter second number: 7
5+7=12

Note: you MUST use "if", not "switch"
Enter a number: 5
Sum = 5
Enter a number: 3
Sum = 8
Enter a number: end
The numbers are: 5 3
The sum is: 8


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		int a, b;
		char operation;

		System.out.print("Enter first number: ");
		a = Integer.parseInt(new Scanner(System.in).nextLine());

		System.out.print("Enter operation: ");
		operation = (char)new Scanner(System.in).nextLine();

		System.out.print("Enter second number: ");
		b = Integer.parseInt(new Scanner(System.in).nextLine());

		if (operation == '+')
		{
			System.out.printf("%1$s + %2$s = %3$s" + "\r\n", a, b, a + b);
		}
		else if (operation == '-')
		{
			System.out.printf("%1$s - %2$s = %3$s" + "\r\n", a, b, a - b);
		}
		else if ((operation == 'x') || (operation == '*'))
		{
			System.out.printf("%1$s * %2$s = %3$s" + "\r\n", a, b, a * b);
		}
		else if (operation == '/')
		{
			System.out.printf("%1$s / %2$s = %3$s" + "\r\n", a, b, a / b);
		}
		else
		{
			System.out.println("Wrong Character");
		}
	}
}