-2

i have a calculator, my problem is that i want to somehow parse the int from the string and then calculate the result, i know subtraction should be first but is there any pattern to do this correctly? calc

Patrikz64
  • 11
  • 1
  • 6

2 Answers2

0

You can use below code to extract the numbers.

    LinkedList<Integer> numbers = new LinkedList<Integer>();

    Pattern p = Pattern.compile("\\d+");


    String line = "9/8*9+3";
    Matcher m = p.matcher(line);
    numbers.clear();
    while (m.find()) {
        numbers.add(Integer.parseInt(m.group()));
    }
Sanjeet
  • 2,385
  • 1
  • 13
  • 22
0

Same approach as Sanjeet, different tools.

List<Integer> numbers = new ArrayList<>();
String expression = "9/8*9+3";
for (String number : expression.split("[\\+-/\\*]")) {
    numbers.add(Integer.parseInt(number));
}

EDIT

Be aware that there limitations to the splitting approaches. Both (Sajeets and mine) will not allow for negative numbers (the minus will be stripped). Also we both assume integers. My approach could be changed to work with floating point numbers though.

cmoetzing
  • 742
  • 3
  • 16