-
2d array grid
hi there, i'm doing an assignment for college and have been asked to make a battleship like game.
i have managed to make a grid using a 2d array which gives an out put as follows:
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
xxxxxxxx
i want to put numbers on the x and y axis as reference so that it would look as follows:
012345678
1xxxxxxxx
2xxxxxxxx
3xxxxxxxx
4xxxxxxxx
5xxxxxxxx
6xxxxxxxx
7xxxxxxxx
8xxxxxxxx
can anyone help? much appreciated!
-
What is so hard about adding some extra print statements to print out the co-ordinates?
-
i've tried but they end up printing next to or after the grid, i'm new to java so i'm not to hinted on all the syntax..he he
-
Ahh so we are supposed to know what you have tried and what is wrong without seeing your code.
-
nevermind, i figured it out, i was putting my print statement for the numbers in the for loop as opposed to putting it before the initialisation of it:
int[][] grid = {{1, 2, 3,4,5,6,7,8,9},{1,2,3,4, 5, 6,7,8,9}};
System.out.println("123456789");
for(int x =0; x<9;x++){
for(int y =0; y<9; y++){
System.out.print("x");
}
System.out.println(x);
}
}
}
sorry for not sending my code, thanks for attempting to help though
-
Code:
String battleship2dArray[][] = new String[8][8];
for (int i = 0; i < battleship2dArray.length; i++){
for (int j = 0; j < battleship2dArray[0].length; j++){
if (j == 0)
{
System.out.print((i+1));
} else if (j == 7) {
System.out.println("X");
} else {
System.out.print("X");
}
}
}
Its going to look like this:
1XXXXXXX
2XXXXXXX
3XXXXXXX
4XXXXXXX
5XXXXXXX
6XXXXXXX
7XXXXXXX
8XXXXXXX
-
Code:
for(int x =0; x<9;x++){
Do not use magic numbers (hard coded values such as the 9). Use the length of the array. That way if your program ever changed to be a 100 x 100 grid then you will not have to change the code of the loops.
-
will do, its still a rough, sort of a psuedo java if you will, just experimenting, thanks alot
-
Another criticism, why are you not printing the contents of the array?
-
Did that help @rjsupaflea?
-
yes thanks @benjamin
uhm, it was, i just changed alot of code while trying to figure it out and forgot to put it all back lol.
-
Ben
I know you are trying to help but posting code hinders the learning process. Especially when it is overly complicated. There is no need for that if statement inside the nested for loops.
-
Well I myself am currently trying to find more efficient ways of doing things and I couldn't think of a easier way to have a println, at the last x, number at first position, and x's in the middle. Still learning though :)
-
Code:
loop row {
print co-ordinate
loop column {
print array(row, col)
}
print new line
}
No if needed.
-
Snap, alright very well. Can't wait till methods flow like that. But I impress myself every day. Working on making a game maker, everything is turning out well, Coming across some difficult things as you can imagine.