0

I want to evaluate the expression from a string..

public static void main(String[] args) {

        String test = "2+3";
        System.out.println(Integer.parseInt(test));
    }

It returns me a NumberFormatException error..How do I fix this?

0

1 Answer 1

4

That won't work with basic java (AFAIK), maybe with some expression evaluator library. You have to parse the string. E.g.:

String[] nums = string.split("+");
List<Integer> numbers = new ArrayList<Integer>();
for(String num : nums) {
    numbers.add(Integer.parseInt(num));
int result = addNumbers(numbers);

Where addNumbers is a method you wrote to add numbers in a list. If you have more operations you have to parse the operators as well, building an expression tree then traversing it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.