Hey guys,
Im new to Java and i am trying to wrap my head around arrays and what not. What i am trying to do is create an array for a puzzle which is 4x4 and has the numbers 1 to 16 so far i have got this

``````public class Puzzle {

public static void main(String[] args) {

Puzzle[][] puzzle = new Puzzle;
// print array in rectangular form
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(1+j);
}
System.out.println("");
}
}
}``````

which gives the output of text
1234
1234
1234
1234

so what i want to be able to do is have:
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16

so not sure how to assign the number to the array positions

## Recommended Answers

``puzzle[i][j]``

For accessing specific index u have to specify its index location...

in loop it will print
puzzle
then
puzzle
and so on....

Two ways:
1: Do some arithmetic using i and j
the first row is 1,2,3,4
The second is 5,6,7,8 which is also 4+1, 4+2, 4+3, 4+4
The third is ... 8+1, 8+2 etc see the pattern?
2: you have a nested loop that you can use to access all the …

## All 7 Replies

``puzzle[i][j]``

For accessing specific index u have to specify its index location...

in loop it will print
puzzle
then
puzzle
and so on....

Two ways:
1: Do some arithmetic using i and j
the first row is 1,2,3,4
The second is 5,6,7,8 which is also 4+1, 4+2, 4+3, 4+4
The third is ... 8+1, 8+2 etc see the pattern?
2: you have a nested loop that you can use to access all the array elements in order (see Majestic's post as well). You need to put 1 in the first, 2 in the second... 16 in the last. You can do this with a simple "counter" variable that starts at 1 and adds 1 each time you use it.

commented: Excellent answer to homework question: Sends the student in the right direction without giving them the answer. +4

This line

``Puzzle[][] puzzle = new Puzzle;``

means that each cell in the 4x4 grid is a "Puzzle". So you have 16 "Puzzle" instances. This may not be what you want. You want to have a 4x4 grid of something. What is the thing you want for each cell in the 4x4 grid? What you want is...

``System.out.print(i*4+j+1);``

What you want is...

``System.out.print(i*4+j+1);``

No. What they want is to learn Java, not just get their homework done for them ready to
copy/paste. Why do you think I went to such lengths to get the OP to work that out for themself? a) It's not a java problem they are having... It's a logic problem.
b) I think that your explanation was rather long and would only confuse them even more. Once someone can see an example in a simple program, they will understand how to use it in more complex applications.
It's not like I did their complete assignment. Gee!!

Thanks for your help guys. Actually got it sorted myself

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.