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");
}
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With