import java.util.Arrays;

/**
 *  Calculator class - Solution to HW 1. 
 * 
 *  @author A. Ozgelen
 */
public class Calculator {
    public static void main(String[] args) {
	// check if the number of arguments are correct
	if(args.length != 3) {
	    System.out.println("Wrong number of arguments"); 
	    printUsage(); 
	    System.exit(1); 
	}
	
	// Print out args
	System.out.println("You have entered: "); 
	// foreach loop. works only on collections which implements Iterable interface
	// variable 'a' executes the body of the loop 'foreach' element in args
	for(String a : args) {
	    System.out.println("[" + a + "]"); 
	}
	// or
	System.out.println(Arrays.toString(args));
	
	
	// check if operands can be parsed as numbers
	double operand1 = 0, operand2 = 0;
	try {
	    operand1 = Double.parseDouble(args[1]); 
	    operand2 = Double.parseDouble(args[2]);
	}
	catch(NumberFormatException e) {
	    System.out.println("Operands have to be numbers");
	    System.out.println(e.getMessage());  
	    printUsage(); 
	    System.exit(1); 
	}
	
	// print result
	char operator = args[0].charAt(0);
	double result = 0;
	switch(operator) {
	case '+':
	    result = operand1 + operand2;
	    break; 
	case '-':
	    result = operand1 - operand2;
	    break;
	case '*':
	    result = operand1 * operand2;
	    break;
	case '/':
	    result = operand1 / operand2;
	    break;
	default:
	    System.out.println("Not a valid operator : [" + operator + "]"); 
	    printUsage(); 
	    System.exit(1); 
	}
	
	// print result
	System.out.println("Result : " + result);
    }
    
    /** prints the command line usage information */
    public static void printUsage() {
	System.out.println("Usage:");
	System.out.println("\t$> java Calculator <operator> <first operand> <second operand>");
	System.out.println("\t where <operator> can be one of the following: '+', '-', '*', '/'");
	System.out.println("\t and operand must be a valid number");
    }
}
