Calculadora - if Aprende programación con ejercicios Java

Lección:

Tipos de datos básicos


Ejercicio:

Calculadora - if 67


Objetivo:

Escriba un programa en java que le pida al usuario dos números y una operación para realizar con ellos (+,-,*,x,/) y muestre el resultado de esa operación, como en este ejemplo:

Introduzca el primer número: 5
Introducir operación: +
Introduce el segundo número: 7
5+7=12

Nota: DEBE usar "si", no "cambiar"


Código:

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");
		}
	}
}