Split input line for calculator

I am trying to split the input given by the user to my calculator. For example, if the user enters "23 + 45 * (1 + 1)" I want this to be divided into [23, +, 45, *, (, 1, +, 1,)].

+5
source share
3 answers

What you are looking for is called lexer. The lexer breaks the input into pieces (called tokens) that you can read.

Fortunately, your lexer is pretty simple and can be written by hand. For more complex lexers, you can use flex(as in Fast Lexicon Analyzer - not Adobe Flex), or (since you use Java) ANTLR (note: ANTLR is much more than just a lexer).

, , ( , , , , , . , ),

\d+
\+
-
*
/
\(
\)

: , . , . ( , , ).

:

List<String>input = new LinkedList<String>();
while(userInputString.length()>0){
    for (final Pattern p : myRegexes){
        final Matcher m = p.matcher(userInputString);
        if(m.find()) {
            input.add(m.group());
            //Remove the token we found from the user input string so that we
            //can match the rest of the string against our regular expressions.
            userInputString=userInputString.substring(m.group().length());
            break;
        }
    }
}

:

  • ^ . , . , .
+7

, . Infix .

Operand1 op Operand2

Shunting-yard, . .

+1

It might be a little messy because I'm still involved, but it splits them into lines.

public class TestClass {

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    ArrayList<String> separatedInput = new ArrayList<String>();
    String input = "";

    System.out.print("Values: ");
    input = sc.next();

    if (input.length() != 0)
    {
        boolean numberValue = true;
        String numbers = "";

        for (int i = 0; i < input.length(); i++)
        {
            char ch = input.charAt(i);
            String value = input.substring(i, i+1);

            if (Character.isDigit(ch))
            { numberValue = true; numbers = numbers + value; }

            if (!numberValue)
            { separatedInput.add(numbers); separatedInput.add(value); numbers = ""; }
            numberValue = false;

            if (i == input.length() - 1)
            {
                if (Character.isDigit(ch))
                { separatedInput.add(numbers); }
            }
        }

    }
    System.out.println(separatedInput);
 }

}

0
source

All Articles