I am a beginner at programming Java looking for some advice.
I have created a very simple program/application asking users to enter commands which in turn display basic shapes on a graphics screen at the user specified location, size and color.
I have used the scanner class to get users input from the keyboard (e.g. user types move 100 150 and the graphics screen pen moves to X = 100, Y = 150 or types circle 100 to display a circle radius 100 at the specified x,y co-ordinate)
I want to return an error message if the user inputs an incorrect command or tried to enter nothing or random keystrokes (e.g. if they misspelled a command or did not specify enough values for the command)
At the moment the program crashes and must be restarted
import java.util.Scanner;
public class Assign1 {
public final static void main(String [] args) {
System.out.println("Let's draw something on the screen!");
GraphicsScreen graphics = new GraphicsScreen();
Scanner input = new Scanner(System.in); // used to read the keyboard
String next; // stores the next line input
String[] one;
do {
System.out.print("Enter a command (\"stop\") to finish : ");
System.out.print("Type 'help' for a list of commands ");
next = input.nextLine();
one = next.split(" ");
String command = one[0];
if(next.contains("help")) {
System.out.println("Type 'move' followed by an X and Y co-ordinate to move the graphical pointer.");
System.out.println("Type 'circle' followed by a radius value to output a circle.");
System.out.println("Type 'line' followed by an X and Y co-ordinate to draw a line.");
System.out.println("Type 'clear' to reset the graphical canvas.");
}
if(next.contains("move")) {
int x = 0;
int y = 0;
x = Integer.parseInt(one[1]);
y= Integer.parseInt(one[2]);
graphics.moveTo(x, y);
}
if( command.equalsIgnoreCase("circle")) {
int radius = 0;
radius = Integer.parseInt(one[1]);
graphics.circle(radius);
}
if(command.equalsIgnoreCase("line")) {
int x = 0;
int y = 0;
x = Integer.parseInt(one[1]);
y= Integer.parseInt(one[2]);
graphics.lineTo(x,y);
}
if(next.contains("clear")) {
graphics.clear();
}
} while ( next.equalsIgnoreCase("stop") == false );
System.out.println("You have decided to stop entering commands. Program terminated!");
graphics.close();
I have all the necessary code for the graphics screen in another document called
graphicscreen.java
I am just looking for suggestion of how I can validate the users text input to give an error message if anything but one of my specific commands are typed.
I have tried using if statements and while loops and others I have found on various web pages but none have yet worked.
Any suggestions much appreciated.
Use
else ifandelse. Anelse ifcondition only gets checked if all theifandelse ifconditions above it evaluated tofalse. Anelseblock only gets run if all theifandelse ifconditions above it evaluated tofalse.