0

I have a string

String numAsString = "8 * 9";

And I want to convert this into an integer, so when I print the integer

int numAsInt = (the code I am asking for);
System.out.println(numAsInt);

The output would be

72

I have tried parseInt and valueOf, but both give an exception cause of the asterisk. If you don't know, the asterisk means multiplication.
Is there a way to do this?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

2 Answers2

4

Parse string by asterisk and multiply parts:

String input = "8 * 9";
String parts[] = input.split("\\*");
int result = 1;
for(String part : parts)
    result *= Integer.parseInt(part.trim());
System.out.println(result);
Rahim Dastar
  • 1,259
  • 1
  • 9
  • 15
-1

You can use something like this and it is easy:

String[] values = numAsString.split("\\*");
numAsInt = Integer.valueOf(values[0].trim()) * Integer.valueOf(values[1].trim());

but If you have a calculation or something with parenthesis, plus, minus and etc, you can use this: Running JavaScript code in java
I think this help you.

Amin
  • 1,643
  • 16
  • 25