File #ytqsry76-11791 - JAVA - Sourcecode

Uploaded by zerodeficit - 31/10/2012 16:52 - 130 Views
Source code
  1. import java.util.Scanner;
  2.  
  3. public class Calculator
  4. {    
  5.     public static void main(String[] args)
  6.     {
  7.         Scanner in = new Scanner(System.in);
  8.         char operator = 'z'; //initialize operator
  9.         double cValue; //current value
  10.         double rhValue; //right hand value
  11.         boolean cont = true;
  12.  
  13.         System.out.print("Enter starting value: ");
  14.         cValue = in.nextDouble();
  15.  
  16.         while(true)
  17.         {
  18.             System.out.print("Select an operator (+, -, *, /), 'c' or 'C' to clear, or 'q' to quit: ");
  19.             String temp = in.nextLine();
  20.             char tempOperator = temp.charAt(0);
  21.  
  22.             if (tempOperator == 'c' || tempOperator == 'C')
  23.             {
  24.                 cValue = 0.0;
  25.                 System.out.println("Current value is: " + cValue);
  26.                 System.out.println();
  27.             }
  28.             else if(tempOperator == 'q')
  29.             {
  30.                 System.out.println("Final result: " + cValue);
  31.                 System.exit(1);
  32.             }
  33.             else if(tempOperator == '+' || tempOperator == '-' || tempOperator == '*' || tempOperator == '/')
  34.             {
  35.                 operator = tempOperator;
  36.                 break;
  37.             }
  38.             else
  39.                 throw new IllegalArgumentException("operator not valid");
  40.         }
  41.  
  42.  
  43.         System.out.println("Enter a right hand value (type double): ");
  44.         rhValue = in.nextDouble();
  45.  
  46.         System.out.println("Math expression: answer " + operator + "= " + rhValue);
  47.         switch(operator)
  48.         {
  49.             case '+': cValue =+ rhValue;
  50.                       break;
  51.             case '-': cValue =- rhValue;
  52.                       break;
  53.             case '*': cValue = cValue * rhValue;
  54.                       break;
  55.             case '/': cValue = cValue / rhValue;
  56.                       break;
  57.         }
  58.  
  59.         System.out.println("Current value is: " + cValue);
  60.     }
  61. }