Search code examples
javacolorsdrawingpen

Changing the colour of a pen in Java via terminal


I'm currently trying to build a drawing tool in Java, controlling a pen using command prompts in the terminal.

So far I've been able to implement commands to tell the pen to move, turn, etc. Now, I'm trying to get my program to respond to the colour command, then I tried putting in a scanner to read the next word. In the example of code I've included, I tried getting the scanner to detect the word "red" and then change the pen colour (the method for which is kept in the "Pen" class).

So, ideally in the terminal, I'd like to type:

colour red

...and get the resulting action to change the colour of the pen to red.

Again for any help you can provide in advance. If there is anything else you'd need to know before you can help, let me know!

 /**
 * Allow the user to draw on the canvas by typing commands.
 */
public void draw()
{   
    boolean finished = false;

    printWelcome();
    printPenLocation();
    while(!finished) {
        LinkedList<String> command = reader.getInput();
        if(!command.isEmpty()) {
            String firstWord = command.get(0);
            switch(firstWord) {
    //Had more examples of case commands here, such as "move", "help", etc ...
                case "colour":
                    Scanner scannerC = new Scanner(System.in);
                    String colour = scannerC.nextLine();
                    if (scannerC.nextLine().equalsIgnoreCase("red"))
                    {
                         pen.setColor(Color.RED);    
                    }
                    else {
                        System.out.println("Unrecognised colour!");
                    }
                    break;
                default:
                    System.out.println("Unrecognised command: " + firstWord);
                    break;
            }
        }
    }
}

The resulting code compiles correctly and throws up no errors, but it doesn't change the pen colour! I'd be grateful for a pair of expert eyes to critique my code.


Solution

  • I can only guess what the code outside of this snippet does, but here is a suggestion:

    My guess is that reader parses an input string as a space separated list. If that is so you should switch the color over the second item in command like so:

    switch(command.get(1).toLowerCase){
    case "red":
        ...
    case "blue":
        ...
    ...
    default:
        System.out.println("Unrecognized color");
    }
    

    That is if you type "color red" and expect the color to change. If not, the error might be somewhere else or the color change code isn't run in the first place. Use system.out.println to find out what part of the code is being run

    Posting this from my phone waiting for a bus so I apologize for possible oversights

    Edit: after seeing the other answer, just combine both of our corrections to solve the case