Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7978297
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T09:27:18+00:00 2026-06-04T09:27:18+00:00

I’ve got the task to program a kind of commandline in Java. It’s meant

  • 0

I’ve got the task to program a kind of commandline in Java.

It’s meant to tests parts of a compiler. You see a promt an can type commands like “read_source “, “parse”, “build_ast”, “ast2cfg”, “print_cfg”, etc.

Is there any library in Java that assists me in building an interpreter (or repl?). I know a python module that would do just what i want: cmd

I wrote something similar myself:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;

interface Command {
    public abstract void action(String[] parameters);
}

public class Repl {
    private String prompt = "\n$ ";

    private HashMap<String, Command> commands;

    private Command nullCommand = null;

    private Command defaultCommand = null;

    public Repl() {
        commands = new HashMap<String, Command>();
    }

    public void setPrompt(String prompt) {
        this.prompt = prompt;
    }

    public void setDefaultCommand(Command defaultCommand) {
        this.defaultCommand = defaultCommand;
    }

    public void setNullCommand(Command nullCommand) {
        this.nullCommand = nullCommand;
    }

    public void addCommand(String name, Command command) {
        commands.put(name, command);
    }

    public void runRepl() {

        if (nullCommand == null) {
            System.err.println("There is no 'nullCommand' specified");
            return;
        }
        if (defaultCommand == null) {
            System.err.println("There is no 'defaultCommand' specified");
            return;
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    System.in));

            String commandName;
            String[] parameters;

            while (true) {
                System.out.print(prompt);

                commandName = reader.readLine();

                if (commandName == null) {
                    nullCommand.action(null);
                } else {
                    parameters = commandName.trim().split("\\s+");

                    Command com = commands.get(parameters[0]);
                    if (com != null) {
                        com.action(parameters);
                    } else {
                        defaultCommand.action(parameters);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Internal error within compiler: stopping compilation");
            System.exit(1);
        }
    }

    /**
     * Exapmpe:
     */
    public static void main(String[] args) {
        Repl repl = new Repl();

        repl.addCommand("printparams", new Command() {
            @Override
            public void action(String[] parameters) {
                System.out.println(Arrays.toString(parameters));
            }
        });

        repl.addCommand("add", new Command() {
            @Override
            public void action(String[] parameters) {
                if (parameters.length == 3) { // {"add", "2", "3"}
                    try {
                        int x = Integer.parseInt(parameters[1]);
                        int y = Integer.parseInt(parameters[2]);
                        System.out.println("Ergebnis: " + (x + y));
                    } catch (NumberFormatException e) {
                        System.out.println("Arguments have to be integers");
                    }
                } else {
                    System.out.println("There have to be two arguments");
                }
            }
        });

        Command helpcommand = new Command() {
            @Override
            public void action(String[] parameters) {
                System.out.println("There is: 'help', 'printparams [PARAMS...]', 'exit' and 'add INTEGER INTEGER'");
            }
        };
        repl.addCommand("help", helpcommand);
        repl.setDefaultCommand(helpcommand);

        Command exitcommand = new Command() {
            @Override
            public void action(String[] parameters) {
                System.out.println("Bye!");
                System.exit(0);
            }
        };
        repl.addCommand("exit", exitcommand);
        repl.setNullCommand(exitcommand);

        repl.runRepl();
    }
}

It works, but it would be nice, for example, if the usage patterns such as “usage: add INTEGER INTEGER [INTEGER…]” for adding two ar more numbers would be generated according to the way the parameters are parsed so that it’s less work to add new commands and to assure they are always consistent.

Also I’m asking myself if that’s overengineered. Would you recommend just writing a loop like this?:

while(true) {
    String command = getUserInput();
    if (command.equals("dothis")) {
        dothis1();
        someMember = dothis2();
    } else if (command.equals("dothat"))
        dothat();
    } else {
        printHelp();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T09:27:20+00:00Added an answer on June 4, 2026 at 9:27 am

    You first answer does seem overly complicated. I use a lot of register code like you have but typically this is when one class is registering itself with another class. The idea that the class would register itself I only use for performance reasons if you have a large number of commands and you were worried about the if {} else if {} chain taking a long time.

    I think the simply solution (albeit not sexy) is the best here.

    while(true) {
        String command = getUserInput();
        if (command.equals("dothis")) {
            dothis1();
        } else if (command.equals("dothat"))
            dothat();
        }
        ...
    }
    

    I always choose the KISS method here with an eye out for performance implications. Complicated code will not only trip up someone else trying to maintain your code but you will be scratching your head as well when you come back to it in 3 months. 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a jquery bug and I've been looking for hours now, I can't
I've got a string that has curly quotes in it. I'd like to replace
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
i got an object with contents of html markup in it, for example: string
Does anyone know how can I replace this 2 symbol below from the string
I have thousands of HTML files to process using Groovy/Java and I need to
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.