1

Am New to Java coding, wanna know how to write a Interpreter program to add two numbers in java.

The interpreter program should read the lines from the source file and do the necessary operations based the line in the source file.

Example : if the first line in the source file is READ A then the interpreter should ask for the input value from the user(Keyboard) store it to A.

Same should be done for READ B and for ADD A,B , PRINT A operations.

The following is the source file Example of my Requirement.

READ A
READ B

ADD A, B

PRINT A

RESULT:
10
20
30
3
  • 3
    Have you written any code yet? If so, please show it and describe any specific problems you are having.
    – Jeremy
    Aug 17, 2011 at 4:15
  • I know basics in core java and some concepts in advance java but this is the first time am trying for interpreter coding. i tried a lot to figure out the code but couldn't able to find the answers.do you have any interpreter coding in java.can you help me out.
    – Jey
    Aug 17, 2011 at 4:24
  • This is not a trivial problem. Generally you will need to define the syntax and grammar of your language and then write parsers and execution code. There are most likely libraries out there which will do the heavy lifting for you. You might want to have a look at (JavaCC javacc.java.net).
    – Carsten
    Aug 17, 2011 at 4:40

3 Answers 3

2

What you're trying to do is to make a scripting language. The wikipedia article I linked you to should get you started, further google searching will provide you with more details. (A good JavaWorld article for scripting languages.)

1

First thing you have to do is break down the problem in several pieces, this is how I would approach this (assuming that you already have java knowledge):

  • Do a simple program, where you read lines from a text file, and then prints them out in console
  • That's the hard part. Once that is done, for every line you should check each line you got from the text file for reserved keywords, i.e. READ, PRINT, ADD.
  • Now, every keyword must have a different behaviour, expects different number of parameters. ie: where you found the ADD keyword, you should expect a number, a comma, and then another number. Then you can do the appropiate action for that keyword.

Hope that can get you started, here I leave you a short example on how to read text files

3
  • +1 for dividing hard looking problems into small chunks. That's how I do it. :)
    – fgysin
    Aug 17, 2011 at 6:13
  • Thanks for your valuable solution. can you guide with the syntax for ADD READ and PRINT.
    – Jey
    Aug 17, 2011 at 6:19
  • Sure, in your code, for every READ command, you should pass that value to a previously declared int variable to store it (i'm assuming that an actual text file for your interpreter should have numbers instead of letters). For the ADD command, it should read the values of A and B, which at this point you already have, add them, and store that result in a third int variable. The PRINT command simply should do a System.out.println of every variable: A, B and "result"
    – Ramses
    Aug 17, 2011 at 15:53
0

Here's pure Java 8 implementation:

import java.io.*;
import java.util.*;
import java.util.function.*;

public class Calculator {
    Map<String, Integer> variables = new HashMap<>();
    Map<String, Consumer<String>> commands = new HashMap<>();

    Scanner scanner = new Scanner(System.in);
    PrintStream out = System.out;

    private Consumer<String> twoArgs(BiConsumer<String, String> bc) {
        return args -> {
            String[] fields = args.split(",\\s*", 2);
            bc.accept(fields[0], fields[1]);
        };
    }

    public Calculator() {
        commands.put("READ", name -> variables.put(name, scanner.nextInt()));
        commands.put("PRINT", name -> out.println(variables.get(name)));
        commands.put("ADD", twoArgs((var1, var2) -> 
            variables.merge(var1, variables.getOrDefault(var2, 0), Integer::sum)));
    }

    public void process(BufferedReader input) {
        input.lines()
            .map(line -> line.split("\\s+", 2))
            .filter(fields -> fields.length == 2)
            .forEach(fields -> 
                commands.getOrDefault(fields[0].toUpperCase(), s -> {})
                        .accept(fields[1]));
    }

    public static void main(String[] args) {
        new Calculator().process(new BufferedReader(new StringReader(
          "READ A\nREAD B\n\n\nADD A, B\n\nPRINT A")));
    }
}

We store variables in variables map (supposed that they are integers) and commands in commands map. The command accepts single string parameter and there's adapter method which may convert two parameter command (like ADD) into single parameter. You may add more commands in the constructor.

Update the main method to read the program source code from external file, resource, etc. Also note that this implementation has no error handling: incorrect input will be either ignored or lead to program crash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.