Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Solution for
Programming Exercise 3.3


THIS PAGE DISCUSSES ONE POSSIBLE SOLUTION to the following exercise from this on-line Java textbook.

Exercise 3.3: Write a program that will evaluate simple expressions such as 17 + 3 and 3.14159 * 4.7. The expressions are to be typed in by the user. The input always consist of a number, followed by an operator, followed by another number. The operators that are allowed are +, -, *, and /. You can read the numbers with TextIO.getDouble() and the operator with TextIO.getChar(). Your program should read an expression, print its value, read another expression, print its value, and so on. The program should end when the user enters 0 as the first number on the line.


Discussion

We need a loop to read and evaluate expressions. It's easiest to use a break statement to end the loop at the appropriate time:

            Repeat indefinitely:
                Get the user's input.
                if the first number is 0:
                    Break out of the loop
                Find the value of the expression
                Display the value.

Getting the user's input involves reading three data values. We need three variables to store these values. It's best to test whether the first number is 0 right after we read it, so the user will just have to type a 0 to end the program, not a complete expression such as 0 + 0. "Repeat indefinitely" can be written as "while (true)":

            while (true):
                Let firstNum = TextIO.getDouble()
                if firstNum is 0:
                    Break out of the loop
                Let operator = TextIO.getChar()
                Let secondNum = TextIO.getlnDouble()
                Find the value of the expression
                Display the value.

To evaluate the user's expression, we have to test the operator to find out which operation to compute. We can do this with either a multi-way if statement or with a switch statement. In the program below, I use a switch. The if statement would be:

                 if ( operator == '+' )
                    value = firstNum + secondNum;
                 else if ( operator == '-' )
                    value = firstNum - secondNum;
                 else if ( operator == '*' )
                    value = firstNum * secondNum;
                 else if ( operator == '/' )
                    value = firstNum / secondNum;
                 else {
                    TextIO.putln("Unknown operator: " + operator);
                    continue;  // back to start of loop
                 }

The computer won't let you get away without the else part of the if statement or the default case in the switch, since that would leave a possibility that the variable, value, is not assigned a value before it is printed out.

This program could be improved by having it print out an error message if the user tries to divide by zero.


The Solution

    public class SimpleCalculator {
       /*  This program evaluates simple expressions such as 2 + 2
           and 34.2 * 7.81, consisting of a number, an operator,
           and another number.  The operators +, -, *, / are allowed.
           The program will read and evaluate expressions until
           the user inputs a line that starts with the number 0.
       */
       public static void main(String[] args) {
          double firstNum;    // First number in the expression.
          double secondNum;   // Second number in the expression.
          char operator;      // The operator in the expression.
          double value;       // The value of the expression.
          TextIO.putln("Enter expressions such as  2 + 2  or  34.2 * 7.81");
          TextIO.putln("using any of the operators +, -, *, /.");
          TextIO.putln("To end, enter a 0.");
          TextIO.putln();
          while (true) {
              /* Get user's input, ending program if first number is 0. */
              TextIO.put("? ");
              firstNum = TextIO.getDouble();
              if (firstNum == 0)
                 break;
              operator = TextIO.getChar();
              secondNum = TextIO.getlnDouble();
              /* Compute the value of the expression. */
              switch (operator) {
                  case '+':
                     value = firstNum + secondNum;
                     break;
                  case '-':
                     value = firstNum - secondNum;
                     break;
                  case '*':
                     value = firstNum * secondNum;
                     break;
                  case '/':
                     value = firstNum / secondNum;
                     break;
                  default:
                     TextIO.putln("Unknown operator: " + operator);
                     continue;  // Back to start of loop!
              } // end switch
              /* Display the value. */
              TextIO.putln("Value is " + value);
              TextIO.putln();
          } // end while
          TextIO.putln("Good bye");
       }  // end main()
    }  // end class

[ Exercises | Chapter Index | Main Index ]

 
 
  Published under free license. Design by Interspire