Exercise
Function calculator, params and return value of Main
Objetive
Write 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 / )
This version must return the following error codes:
1 if the number of parameters is not 3
2 if the second parameter is not an accepted sign
3 if the first or third parameter is not a valid number
0 otherwise
Example Code
public class Main
{
public static int main(String[] args)
{
if (args.length != 3)
{
System.out.println("Error!");
System.out.println("Usage: number1 operand number2");
System.out.println("Where operand can be + - / * x ·");
return 1;
}
try
{
int number1 = Integer.parseInt(args[0]);
int number2 = Integer.parseInt(args[2]);
switch (args[1])
{
case "+":
{
System.out.println(number1 + number2);
break;
}
case "-":
{
System.out.println(number1 - number2);
break;
}
case "/":
{
System.out.println(number1 / number2);
break;
}
case "*":
case "x":
case "·":
{
System.out.println(number1 * number2);
break;
}
default:
{
System.out.println("Error!");
System.out.println("Operand must be + - / * x or ·");
return 2;
break;
}
}
}
catch (RuntimeException e)
{
System.out.println("Error!");
System.out.println("Not a valid number");
return 3;
}
return 0;
}
}