Expert's help needed on Java 2d Array:
boolean flag = true;
while(true){
String consoleInput = in.nextLine();
commands.add(cmd);
switch (consoleInput) {
case "right":
//how to turn right in 2d array
break;
case "left":
//how to turn left in 2d array
break;
case "exit":
flag=false;
break;
default:
int moveForward = consoleInput;
//how to move forward in 2d array
}
Need to capture everything in 2d array
So that I can track the path of the car.
I request for help from some expert here as I am stuck.
For turning left or right you simply need a variable that tracks the direction, and then choose a value for that variable that represents the direction, for example the points of a compass
North, East, South, West, or0,1,2,3where 0=North, 1=East, etc:To turn simply update the variable, here is a turn left example:
To track the car location simply use a Point variable:
As for how to move forward, you simply adjust the loacation of your car based on the direction variable, we can do this easily with
ifstatements:And finally we store it in the array:
The complete code could go in it's own class a bit like this:
Then using the following input from the main method (Where the car starts facing east in the above code):
We get this output with the blank grid at the start, and the final printed grid shows the complete path and the final location:
You will need to build in some error checking to make sure the car does not go outside the grid/array, and you will need to fix up a few other things like your input method, but it will get you started.
Edit: If you want to start outside the area for exampl elike this
Point startLocation = new Point(-1, 0);, then remove the line that prints the start location:And change the moveForward method to not modify the array if the start is outside the left side by adding this
ifcheck: