4

I'm trying to make a simple text based calculator in java my first program, EVER and I can't figure out how to turn an input String into a variable opOne. I would then attempt to operate numOne against numTwo using opOne as the operator. Code is as follows:

import java.io.*;
import java.math.*;

public class ReadString {

   public static void main (String[] args) {


      System.out.print("Enter the first number: ");


      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
      int numOne = 0 ;
      int numTwo = 0 ;
      String opOne = null;

      while(true){
      try {
          numOne = Integer.valueOf(br.readLine());
          break;
      } catch (IOException error) {
         System.out.println("error; try again.");
         System.exit(1);
      }
      catch (NumberFormatException nfe) {
          System.out.println("error;try again.");

      }

      }

      System.out.print("Enter the second number: ");

      while(true){
      try {

          numTwo = Integer.valueOf(br.readLine());
          break;
       } catch (IOException error2) {
          System.out.println("error");
          System.exit(1);
       } catch (NumberFormatException nfe) {
          System.out.println("error;try again.");

       }
      }

      System.out.println("What would you like to do with " + numOne + " and " + numTwo + "?");

      try {
          operator = br.readLine();
       } catch (IOException ioe) {
          System.out.println("error");
          System.exit(1);
       } catch (NumberFormatException nfe) {
          System.out.println("error");

       } 
   }
}
Kailua Bum
  • 1,368
  • 7
  • 25
  • 40
Cory Liseo
  • 81
  • 1
  • 2
  • 8
  • *"text based calculator"* Use [`ScriptEngine`](http://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngine.html) instead. E.G. 1) [in web page (applet)](http://stackoverflow.com/a/12023586/418556) 2) [non GUI](http://stackoverflow.com/a/8162055/418556) 3) [simple GUI](http://stackoverflow.com/a/6426684/418556) 4) [nice GUI](http://stackoverflow.com/a/7441804/418556).. – Andrew Thompson Mar 02 '13 at 01:21

3 Answers3

6

The simplest way of doing this would be a sequence of if-then-else statements:

if ("+".equals(opOne)) {
    res = numOne + numTwo;
} else if ("-".equals(opOne)) {
    res = numOne - numTwo;
} ...

An advanced way would be to define an interface for your operators, and putting the instances in a Map container:

interface Operation {
    int calculate(int a, int b);
}

static final Map<String,Operation> opByName = new HashMap<String,Operation>();
static {
    opByName.put("+", new Operation() {
        public int calculate(int a, int b) {
            return a+b;
        }
    });
    opByName.put("-", new Operation() {
        public int calculate(int a, int b) {
            return a-b;
        }
    });
    opByName.put("*", new Operation() {
        public int calculate(int a, int b) {
            return a*b;
        }
    });
    opByName.put("/", new Operation() {
        public int calculate(int a, int b) {
            return a/b;
        }
    });
}

With a map initialized like this, you can perform calculations as follows:

int res = opByName.get(opOne).calculate(numOne, numTwo);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

There's no way you can convert a Java string to an operator. It's not a Java data type.

   double Calculate(String opOne, double numOne, double numTwo) {  
      if (opOne.equals("+"))  
        return numOne + numTwo;  
      else if (opOne.equals("-"))  
        return numOne - numTwo;  
      else if (opOne.equals("*"))  
        return numOne * numTwo; 
      else if (opOne.equals("/"))  
        return numOne / numTwo;   
    } 
daOnlyBG
  • 595
  • 4
  • 20
  • 49
Snippet
  • 1,522
  • 9
  • 31
  • 66
1

Computer, by itself, does not know what an operator (in human language) is, so you need to tell the computer to do that.

String opOne;

try {
    opOne = br.readLine();
} catch (IOException ioe) {
    System.out.println("error");
    System.exit(1);
}

switch (opOne) {  //Note: String in switch is possible only from Java 7, check your version
     "+": System.out.println('Result: ' + (numOne + numTwo)); break; 
     "-": System.out.println('Result: ' + (numOne - numTwo)); break;
     // and so on...
}
luiges90
  • 4,493
  • 2
  • 28
  • 43