Calculator - switch Learn programming Java



Lesson:

Basic Data Types


Exercise:

Calculator - switch


Objetive:

Write a java program that 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 the first number: 5
Enter the operation: +
Enter the second number: 7
5+7=12

Note: You MUST use 'switch', not 'if'.


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());

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



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.