Function calculator, params of Main Learn programming Java

Lesson:

Functions


Exercise:

Function calculator, params of Main 9


Objetive:

Create a java program to calculate a sum, subtraction, product or division, analyzing the command line parameters:

calc 5 + 379

(Parameters must be a number, a sign, and another number; allowed signs are + - * x / )


Code:

public class Main
{
	public static void main(String[] args)
	{
		char operation = (char)args[1];

		int number1 = (int)args[0];
		int number2 = (int)args[2];

		int result = 0;
		if (args.getLength() != 3)
		{
			switch (operation)
			{
				case '+':
					result = number1 + number2;
					break;
				case '-':
					result = number1 - number2;
					break;
				case 'x':
				case 'X':
				case '*':
					result = number1 * number2;
					break;
				case '/':
					result = number1 / number2;
					break;
			}
			System.out.printf("Result: %1$s" + "\r\n", result);
		}
		else
		{
		System.out.println("Error in arguments");
		}
	}
}