0

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.

MaSu
  • 3
  • 3

2 Answers2

0

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, or 0,1,2,3 where 0=North, 1=East, etc:

//Variable to track direction
public int direction = 0;

To turn simply update the variable, here is a turn left example:

public void turnLeft(){
    if(direction == 0)
        direction = 3;
    else
        direction = direction-1;
}

To track the car location simply use a Point variable:

Point location = new Point(0,0);

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 if statements:

public void moveForward(){
    //North == 0
    if(direction = 0)
        location.y = location.y-1;
    //East  = 1
    else if(direction == 1)
        location.x = location.x+1;
    //And so on...
}

And finally we store it in the array:

//show the new car location
pathArray[location.x][location.y] = 'X';

The complete code could go in it's own class a bit like this:

public class CarTracker{
    //2d array to store path
    char[][] pathArray = new char[10][10];
    
    //Variable to track direction
    //Start facine east (1)
    int direction = 1;
    
    //Track car location
    Point location = new Point(0,0);
    
    //Car symbol
    char car = 'X';
    char trail = 'O';
    
    public void start(String commands, Point startLocation){
        //read input commands
        Scanner in = new Scanner(commands);
        
        //Set start location
        location = startLocation;
        
        //Fill the array with blanks so that it prints nicely
        for (int y = 0; y < pathArray.length; y++){
            for (int x = 0; x < pathArray[y].length; x++)
                pathArray[y][x] = ' ';
        }
        
        //Show the initial starting point for the print command
        pathArray[location.y][location.x] = car;
        
        //loop until exit
        while(in.hasNext()){
            String consoleInput = in.nextLine();
            switch (consoleInput){
                case "right":
                    turnRight();
                    break;
                case "left":
                    turnLeft();
                    break;
                case "exit":
                    System.exit(0);
                    break;
                case "print":
                    print();
                    break;
                case "forward":
                    moveForward();
                    break;
                default:
                    System.out.println("Invalid command: "+consoleInput);
                    break;
            }
        }
    }

    public void turnLeft(){
    if (direction == 0)
        direction = 3;
    else
        direction = direction - 1;
    }
    
    public void turnRight(){
    if (direction == 3)
        direction = 0;
    else
        direction = direction + 1;
    }
    
    public void moveForward(){
        //change previous character to a trail or mark the start
        pathArray[location.y][location.x] = trail;
        
        //North = 0
        if(direction == 0)
            location.y = location.y-1;
        //East  = 1
        else if(direction == 1)
            location.x = location.x+1;
        //South = 2
        else if(direction == 2)
            location.y = location.y+1;
        //West = 3
        else
            location.x = location.x-1;
        
        //show the new car location
        pathArray[location.y][location.x] = car;
    }
    
    public void print(){
        System.out.println("Current Location:");
        //loop the array and print
        for (int y = 0; y < pathArray.length; y++){
            for (int x = 0; x < pathArray[y].length; x++)
                //Print each part of the grid
                System.out.print("[" + pathArray[y][x] + "]");
            //move to the next row
            System.out.println();
        }
    }
}

Then using the following input from the main method (Where the car starts facing east in the above code):

CarTracker tracker = new CarTracker();

String commands = 
"print\n" +
"forward\n" +
"forward\n" +
"right\n" +
"forward\n" +
"forward\n" +
"forward\n" +
"left\n" +
"forward\n" +
"forward\n" +
"left\n" +
"forward\n" +
"right\n" +
"forward\n" +
"print";

Point startLocation = new Point(0, 4);
    
tracker.start(commands, startLocation);

We get this output with the blank grid at the start, and the final printed grid shows the complete path and the final location:

Current Location:
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[X][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
Current Location:
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[O][O][O][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][O][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][O][ ][O][X][ ][ ][ ][ ]
[ ][ ][O][O][O][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]

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:

//The initial starting point
//pathArray[location.y][location.x] = car;

And change the moveForward method to not modify the array if the start is outside the left side by adding this if check:

public void moveForward(){
//change previous character to a trail or mark the start
if(location.x >= 0){
    pathArray[location.y][location.x] = trail;
}
sorifiend
  • 5,927
  • 1
  • 28
  • 45
  • Thanks. Variable car is char[][] car= new char[column][row]; right? I will give it a try and let you know – MaSu Aug 29 '22 at 03:13
  • @MaSu No, the car is just the symbol stored in the 2d array. I have edited my post with more information showing how it might work. – sorifiend Aug 29 '22 at 04:51
  • Awesome.. One more small help please. Car's position should be outside on North West(Left Top) as shown below. Outside this element 'X [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]' – MaSu Aug 29 '22 at 05:06
  • Feel free to change the code to work like that. But note that you can`t store data outside of the array bounds, so the first command would have to be forward before you tried to store any data. – sorifiend Aug 29 '22 at 05:16
  • @MaSu See the edit at the end with a tip on how to do it. – sorifiend Aug 29 '22 at 05:21
  • In the above solution if I make char[][] pathArray = new char[5][10] instead of new char[10][10];. Just trying to call print() method with out any operation and it is failing. Strange. Please help me here. – MaSu Aug 29 '22 at 11:46
  • @MaSu Ahh, there were a few mistakes, first, this line was backwards in the print method, just swap x and y like shown `System.out.print("[" + pathArray[y][x] + "]");`, and secondly the lines `pathArray[location.y][location.x] = trail;` and `pathArray[location.y][location.x] = car;` were backwards, I had x first and y second, but it should be like I showed here. I have updated the answer to suit – sorifiend Aug 30 '22 at 01:09
0
public void start(String commands, Point startLocation) {
        //read input commands
        Scanner in = new Scanner(commands);

        //Set start location
        location = startLocation;

        //Fill the array with blanks so that it prints nicely
        for (int y = 0; y < pathArray.length; y++) {
            for (int x = 0; x < pathArray[y].length; x++)
                pathArray[y][x] = ' ';
        }

        //Show the initial starting point for the print command
//        pathArray[location.x][location.y] = bullDozer;

        //loop until exit
        while (in.hasNext()) {
            String consoleInput = in.nextLine();
            switch (consoleInput) {
                case "right":
                    turnRight();
                    break;
                case "left":
                    turnLeft();
                    break;
                case "exit":
                    System.exit(0);
                    break;
                case "print":
                    print();
                    break;
                case "forward":
                    moveForward();
                    break;
                default:
                    System.out.println("Invalid command: " + consoleInput);
                    break;
            }
        }
    }
MaSu
  • 3
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 02 '22 at 05:40