0

I am attempting to create a calculator using Java. I know that I will need to create a parser to convert the user's data from a string to doubles and a character.

I was wondering if, by creating the parser, the data that the user enters (for example 7 / 5 ) would be already separated or if I would need to separate the data somehow.

I was also wondering how the operator would effect the parser and if there was a way to retrieve that separately. I had attempted to use input.next(); to retrieve the operand but I think because I am using the parser, it may not work.

Here is my code:

String rawUserInt;
String method;
double answer;
Scanner input = new Scanner(System.in);

        System.out.println("Please input the equation you would like to solve");

        double userInt1 = Double.parseDouble(rawUserInt);
        method = input.next();
        double userInt2 = Double.parseDouble(rawUserInt);
Adaisha
  • 21
  • 3

1 Answers1

0

Typically. processing of formal languages (like expressions) is split into lexical analysis and parsing. The lexical analyzer would split up the input into tokens and also ignore irrelevant characters like white space. It also determines the type of the token. In your example this would lead to double(7), operator(/), double(5).

The next step is done by the parser, which assembles the tokens into an abstract syntax tree (AST) according to the grammar for the formal language. In the example this would give

      "/"
     /   \
    7     5

It is then easy to evaluate the expression using the tree structure.

In simple cases like yours, you may not need all layers as explicit components. For example it is possible to evaluate an expression directly after the lexical analysis without building an AST first.

Henry
  • 42,982
  • 7
  • 68
  • 84