0

I am developing my own shell(command prompt). [When
a user enters a built-in command, the shell is required to search and execute the respective code accordingly.]

I have created my code using command split, and command parameters in order to store my commands. but one thing I'm confused about is that making a command that is not in the list. I think of using if statement to print invalid comment (for example)

if (command!="exit")||(command!="about")||(command!="date")||(command!="time")||(command!="hist")||(command!="notepad")
                    ||(command!="")||(command!="hist -h")||(command!="hist -l")||(command!="c"){

System.out.println("invalid command");
}

but this statement is way too much if there are tons of command line.. so is there an easy way of implementing it !?

2 Answers 2

1

If this java and all commands are Strings and input command is also a String you can simplify what you are trying to do by creating a list of valid commands and do a contains check.

List<String> validCommands = Arrays.asList("exit", "about", "date");
if (!validCommands.contains(command)) {
    System.out.println("invalid command");
}

That being said there are better ways to maintain a list of valid command outside java program such as properties file and load list of valid commands from that file. This will make your program more maintainable.

Sign up to request clarification or add additional context in comments.

2 Comments

What if command includes integer for example.. like if i want to print previous x number of used commands, ill be using (hist x) as X indicates integer number of used commands.. and hist = history of commands
hist x will still be a string, string combined with integer can be cast to a string
0

Use a Map<String, Command>, to keep track of the available commands. If the command is not in the map then it's invalid. For example:

public class Shell {
    private final Map<String, Command> supportedCommands;

    public Shell(Map<String, Command> supportedCommands) {
        this.supportedCommands = supportedCommands;
    }

    public void execute(String command, String[] args) {
        Command c = supportedCommands.get(command);
        if (c == null) {
            System.out.println("invalid command");
        } else {
            c.execute(args);
        }
    }


    public interface Command {
        public void execute(String[] args);
    }

}

1 Comment

same issue as above solution (((((What if command includes integer for example.. like if i want to print previous x number of used commands, ill be using (hist x) as X indicates integer number of used commands.. and hist = history of commands )))))

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.