Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*; // for StringTokenizer, Scanner
- public class SimpleCalculator {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- String theString = "";
- int length;
- // num1, num2 and answer are declared as type double
- double num1 = 0;
- double num2 = 0;
- double answer = 0;
- String first = "";
- String operator = "";
- String second = "";
- boolean error;
- do {
- // 'theString' is the text the user types in
- System.out.print("Type your sum (q = quit): ");
- theString = scan.nextLine();
- if (theString.equals("q")) {
- // quit the program
- System.exit(0);
- } // end if
- // assign the variable 'length' to length of String 'theString'
- length = theString.length();
- StringTokenizer t = new StringTokenizer(theString, "+-*/%");
- // separate theString into two numbers, separated by the operator
- first = t.nextToken();
- try {
- second = t.nextToken();
- error = false;
- }
- catch (Exception e) {
- // there wasn't a second token because it didn't find an operator
- System.out.print("Error! Use the format: <number>+-*/%<number>");
- System.out.println();
- error = true;
- } // end try/catch
- } while (error);
- // convert strings to doubles
- num1 = Double.parseDouble(first);
- num2 = Double.parseDouble(second);
- // is the first letter a minus sign?
- String firstLetter;
- firstLetter = theString.substring(0, 1);
- // is the first number negative?
- if (firstLetter.equals("-" )) {
- num1 *= -1;
- } // end if
- // find which operator was used
- for (int i = 1; i < length; i++) {
- operator = theString.substring(i, i+1);
- if (operator.equals("+" ) || operator.equals("-" ) || operator.equals("*" ) ||
- operator.equals("/" )) {
- break;
- } // end if
- } // end for
- // compute answer
- switch(operator) {
- case "+" : answer = num1+num2; break;
- case "-" : answer = num1-num2; break;
- case "*" : answer = num1*num2; break;
- case "/" : if (num2 == 0) {
- System.out.print("Division by zero error!");
- System.exit(0);
- } // end if
- answer = num1/num2; break;
- case "%" : answer = num1%num2; break;
- default : System.out.print("Wrong operator.");
- System.exit(0);
- } // end switch
- // display original sum and answer
- System.out.print(num1+operator+num2+"="+answer);
- } // end main()
- } // end class SimpleCalculator
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement