Hi All,
Before you look at my code, let me warn you that I know it's a mess...I'm suppose to create a very simple calculator that uses command line parameters. I'm not suppose to use any exception handlers but it is suppose to display a message when one of the operands is not an integer or if there are less or more than three args.
I've got all sorts of "if" loops going on. It compiles but is not running properly. Any guidance would be appreciated.
public class ExceptDemo1b
{
//Main Method with three arguments
//args[0]: operator
//args[1]: operand1
//args[2]: operand2
public static void main(
String[] args)
{
//Declare and initialize variables
int result = 0;
int operand1 = Integer.parseInt(args[1]);
int operand2 = Integer.parseInt(args[2]);
if (args.length != 3)
{
System.out.println("Usage:
java Calculator operator operand1 operand2");
System.exit(0);
}
if((operand1 >= 0) || (operand1 < 0))
{
switch (args[0].charAt(0))
{
case '+': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
break;
case '-': result = Integer.parseInt(args[1]) -
Integer.parseInt(args[2]);
break;
case '*': result = Integer.parseInt(args[1]) *
Integer.parseInt(args[2]);
break;
case '/': result = Integer.parseInt(args[1]) /
Integer.parseInt(args[2]);
}
//Display the result
System.out.println(args[1]+ ' ' +args[0]+ ' ' +args[2]+ "=" +result);
}
else
{
System.out.println("Wrong input " + operand1);
System.exit(0);
}
if ((operand2 >= 0) || (operand2 < 0))
switch (args[0].charAt(0))
{
case '+': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
break;
case '-': result = Integer.parseInt(args[1]) -
Integer.parseInt(args[2]);
break;
case '*': result = Integer.parseInt(args[1]) *
Integer.parseInt(args[2]);
break;
case '/': result = Integer.parseInt(args[1]) /
Integer.parseInt(args[2]);
}
//Display the result
System.out.println(args[1]+ ' ' +args[0]+ ' ' +args[2]+ "=" +result);
System.out.println("Wrong input " + operand2);
System.exit(0);
}
}
Thanks,
Marie