0

I have a text file which contains something like this - 23+3 i have to do the math and write the ans in a different text file. i have tried with scan.nextInt() method.but shows exception when scanning "+" any help here with ignoring the other chars ??

  • 4
    Read the line as a String, then parse it through a utility method to get your result. – Kon Aug 11 '14 at 04:48
  • 1
    possible duplicate of [Evaluating a math expression given in string form](http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) – Nir Alfasi Aug 11 '14 at 04:58

2 Answers2

3

You could use regex to match for numbers like,

String regex = "[0-9]+"; or

String regex = "\\d+";

Where the + means "one or more" and \d means "digit".

Note: the "double slash" gives you one slash. "\d" gives you: \d

Pass the regex to pattern : Pattern p = Pattern.compile(regex); and then look for a match in your input string Matcher m1 = p.matcher(inputString);

Raj Saxena
  • 852
  • 10
  • 18
0

Let's assume you only have an addition operator. You could split on the + symbol.

String[] arr = "23+3".split("+"); // returns ['23', '3']

Now you will iterate through your String array, convert each entry to an Integer, and sum the entire array.

You can extend this approach to use subtraction/multiplication/division etc. However you may want to look up as Abstract Syntax Tree. Take a look at this StackOverflow answer:

How to construct an abstract syntax tree

Community
  • 1
  • 1
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159