Reputation: 363
I'm having some trouble getting the correct output when printing an array. Essentially what I'm trying to do is set up an array in the main method, then send that array to another method that would print out something like this:
89 12 33 7 72 42 76 49
69 85 61 23
With it being 3 spaces to the right and starting a new print line after the 8th number. Seems easy enough but I get something like this instead.
89
69 85 61 23
It doesn't print out the values between position 1 and 7 for some reason. This is what I have.
public class Test
{
public static void main (String [] args)
{
int [] myInches = {89,12,33,7,72,42,76,49,69,85,61,23};
printArrayValues(myInches);
}
public static void printArrayValues(int [] myInchesParam) {
for (int i = 0; i < 8; i++) {
System.out.print(" " + myInchesParam[i]);
System.out.println();
for (i = 8; i < 12; i++) {
System.out.print(" " + myInchesParam[i]);
}
}
}
}
Should I use a do-while instead? Or can I still do it with a for loop and I'm just doing it wrong?
Upvotes: 1
Views: 700
Reputation: 11042
The problem is you that you are using the same variable in two nested for
loops. This will cause the outer array to stop after the first iteration and print only the values in the second line.
Just use one loop and print a new line if i > 0 && i % 8 == 0
:
public static void printArrayValues(int[] myInchesParam) {
for (int i = 0; i < myInchesParam.length; i++) {
if (i > 0 && i % 8 == 0)
System.out.println();
System.out.print(" " + myInchesParam[i]);
}
}
Alternatively you can just use i % 8 === 7
to insert a new line afterwards:
public static void printArrayValues(int[] myInchesParam) {
for (int i = 0; i < myInchesParam.length; i++) {
System.out.print(" " + myInchesParam[i]);
if (i % 8 == 7)
System.out.println();
}
}
But you could have a trailing new line in some cases with this last solution.
Upvotes: 1
Reputation: 98
Well, what is happening is that in the loop i starts as 0, then when it reaches the second loop you set i to 8, and thus the condition i < 8 is no longer valid. Easiest fix would be to not nest your loops but have
for (int i = 0; i < 8; i++) {
System.out.print(" " + myInchesParam[i]);
}
System.out.println();
for (i = 8; i < 12; i++) {
System.out.print(" " + myInchesParam[i]);
}
instead. Even nicer is probably
for (int i = 0; i < 12; i++) {
System.out.print(" " + myInchesParam[i]);
if(i==7) {
System.out.println();
}
}
Upvotes: 1
Reputation: 248
There are many ways to solve this but one would be using the modulo operator to check if 8 entries have already been printed. You add 1 to i because your array is 0 indexed.
for (int i = 0; i < myInchesParam.length; i++) {
System.out.print(myInchesParam[i] + " ");
if((i + 1) % 8 == 0) {
System.out.println();
}
}
EDIT: The benefit of this method is that it works for any array length. Some of the other suggestions will not.
Upvotes: 1