Reputation: 19
I've been trying to make a program that will just write 2D arrays with the following text through print format. The output I am expecting supposedly should look like this, don't mind the bold points they are meant for new line:
Name : Florence
Tel. # : 735-1234
Address: Chicago
*
Name : Joyce
Tel. # : 983-3333
Address: Evanston
*
Name : Becca
Tel. # : 456-3322
Address: Oak Park
This is my code so far:
public static void main(String[] args) {
String[][] entry = {
{"Florence", "735-1234", "Chicago"},
{"Joyce", "983-3333", "Evanston"},
{"Becca", "456-3322", "Oak Park"}};
for (int i = 0; i < entry.length; i++) {
for (int q = 0; q < entry[i].length; q++) {
System.out.printf("\n%s\n%s\n%s",
"Name : " + entry[i][q],
"Tel. # : " + entry[i][q],
"Address: " + entry[i][q]);
}
System.out.println();
}
}
But my output only shows this:
*
Name : Florence
Tel. # : Florence
Address: Florence
Name : 735-1234
Tel. # : 735-1234
Address: 735-1234
Name : Chicago
Tel. # : Chicago
Address: Chicago
*
Name : Joyce
Tel. # : Joyce
Address: Joyce
Name : 983-3333
Tel. # : 983-3333
Address: 983-3333
Name : Evanston
Tel. # : Evanston
Address: Evanston
*
Name : Becca
Tel. # : Becca
Address: Becca
Name : 456-3322
Tel. # : 456-3322
Address: 456-3322
Name : Oak Park
Tel. # : Oak Park
Address: Oak Park
Any tip or advice will be greatly appreciated.
Upvotes: 2
Views: 191
Reputation: 37
The easiest way to do this would be to use Arrays.deepToString(entry)
.
However that comes at the cost that you cannot specify anything between the array elements. If your priority is to display the additional Text, I suggest the other answer already present. If your priority is a well working, understandable and fast-to-code solution, then my suggestion works better.
Upvotes: 1
Reputation: 574
though most of the code you've written is correct, you just don't need 2nd for loop. Below is why
when q=0, your code is printing
Name = entry[0][0]
Tel. #= entry[0][0]
Address = entry[0][0]
when q=1, your code is printing
Name = entry[0][1]
Tel. #= entry[0][1]
Address = entry[0][1]
when q=2, your code is printing
Name = entry[0][2]
Tel. #= entry[0][2]
Address = entry[0][2]
I think, here you got fair idea on what happens next. Above process goes on till i<3 and q<3.
This type of printing you can avoid just by excluding 2nd for loop in your code and add something like below
for ( int i= 0; i < entry.length; i++){
System.out.printf("\n%s\n%s\n%s", "Name : " + entry[i][0], "Tel. # : " +entry[i][1], "Address: " + entry[i][2]);
System.out.println();
}
when above code snippet runs, you can see the expected output as you mentioned above.
when i=0, your code is printing
Name = entry[0][0]
Tel. #= entry[0][1]
Address = entry[0][2]
Next 2 steps you can follow I guess.
Hope this is helpful.
Upvotes: 2