1

wIt's very confusing, I know, but essentially what I am trying to figure out is how to take the information from a file and parse through it in order to get the equations in the file.

Like say, the file contains the problem 8 + 5 = 13

I want my program to read the file and then take the integers 8 and 5, recognize the operator symbol, and then do the math so that it can compare it to the final answer in order to grade the problem.

I have these lines of code already, which can capture the first integer, but I'm stuck on getting the operator and the second integer so that I can get the program to do the math.

int whiteSpace1 = fileContent.indexOf(" ");
        int first = Integer.parseInt(fileContent.substring(0, whiteSpace1));
        int second = Integer.parseInt(fileContent.substring(whiteSpace1, 2));

I have no real clue where to go from here in order to get the operator and second int. Please help.

Extra Info: There will not always be just two operands and they won't always be ints. I also cannot use arrays or regex or a try/catch.

CherryBomb95
  • 153
  • 2
  • 12

1 Answers1

0

For simple expression parsing, consider using StreamTokenizer.

Simple example code snippet to see how it works:

StreamTokenizer tokenizer = new StreamTokeniner(new StringReader(fileContent));
while (tokenizer.nextToken() == Tokenizer.TT_EOF) {
  if (tokenizer.ttype > 32) {
    System.out.print("token type: '" + ((char) tokenizer.ttype) + "'");
  } else {
    System.out.print("token type: " + tokenizer.ttype);
  }
  System.out.println(" string value: " + tokenizer.sval + 
                     " numeric value: " + tokenizer.nval);
} 
Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51