r/programminghelp • • Jul 14 '20

Java A question about Java

So in java you can make calculations like 3+1 now my question is if i ask for input lets say in a calculator and the second string is + (the first one would be 3 and the third one would be 1) how can i convert the + from a string into a symbol that i can make calculations with

4 Upvotes

5 comments sorted by

2

u/inxaneninja Jul 14 '20

First convert the first and third string into integers, you'll find ways to do it online.

The second string can't exactly be converted to an actual operator because that's fundamentally wrong. You'll need to make an if statement that'll check if for example the operator is a plus, and then do addition etc.

int result;
if (op.equals("+")) {
    result = a + b;
} else if (op.equals("-")) {
    result = a - b;
} ...

a - the first number

b - the second number

op - the operator the user typed in

You can define more operators like multiplication etc.

2

u/i_do_jokes Jul 15 '20

Yeah that's what i have been trying to avoid, making if statements. But i asked my friend and he said its not possible. Thanks anyways i appreciate it :)

1

u/inxaneninja Jul 15 '20

Why avoid if statements?

1

u/i_do_jokes Jul 16 '20

I was trying to make it more "compact"

2

u/[deleted] Jul 14 '20

You'll have to use an if statement or a switch statement to check the second string, if it's a plus sign "+" then you'll perform addition on the two other strings (After converting them to integers, etc).