Garwaire Garwaire - 1 year ago 111
Java Question

Changing the colour of a pen in Java via terminal

Hello Stackoverflow community! I'm a first-time programmer and 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.

Thanks 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;

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(;
String colour = scannerC.nextLine();
if (scannerC.nextLine().equalsIgnoreCase("red"))
else {
System.out.println("Unrecognised colour!");
System.out.println("Unrecognised command: " + firstWord);

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.

Answer Source

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:

case "red":
case "blue":
    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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download