English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

i'm trying to get java code to print exactly what is below but apart from the 4rth line( 2 1).
1 1
1 2
1 3
2 1 //problem here, i don't want 2,1
2 2
2 4
2 6
2 8
3 1
3 2
3 3

does anyone know what i need to change in my code?
Thanks!!


class ForLoop
{

public static void main(String[] args)

{

for(int i = 1; i < 4; i++)

{


for(int j = 1; j < 4; j++)
{
System.out.println(i+" "+j);


if(i == 2)
{
for (j = 2; j<9; j=j+2)
System.out.println(i+" "+j);
}

}


}

}

}

2007-03-17 05:54:42 · 3 answers · asked by Anonymous in Computers & Internet Programming & Design

3 answers

The reason why you get 2.1 is that you're checking for i==2 AFTER you print the normal loop starting with 1. Move that loop in the else clause of if(i==2)

A more elegant solution would be to put only the println method in the if(i==2) block, and thus have only a single inner loop over j.

2007-03-17 06:07:40 · answer #1 · answered by kite_snow_boarder 1 · 1 0

My idea for the loop is:

for(int i = 1; i <=3; i++)
  for(int j = 1; j <=4; j++)
    if(!(i == 2 && j == 1))
      System.out.println(i + " " + j);

2007-03-17 13:40:05 · answer #2 · answered by nightgirl1200 4 · 0 0

Your code is perfectly fine after you add this

if( i != 2 )

before your first System.out.println

2007-03-19 05:01:38 · answer #3 · answered by Liviawarty J 2 · 0 0

fedest.com, questions and answers