반복문을 응용해서 중첩하여 사용하는 방법이 있습니다.
가장 많이 활용되는 for문의 중첩을 해보겠습니다.
public class DupFor {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=0; i<3; i++) {
System.out.println("변수 i의 값 : "+ i);
for(int j=0; j<3; j++)
System.out.println("***변수 j의 값 : " + j);
}
}
}
i=0부터 반복이 시작이 되어서, j의 값이 0,1,2로 증가하고 j의 반복이 끝나면 i=1이 되어서 또 j의 값이 증가하고 그렇게 i가 2가 되어서 반복문이 진행된 후에 조건에 따라 더이상 반복을 하지않고 끝나게 됩니다.
이것을 응용하면 우리는 이제 구구단을 간단하게 출력하는 프로그램을 만들 수 있게 됩니다.
public class ByTimes {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=2; i<10; i++) {
for(int j=1; j<10; j++)
System.out.println(i + " x " + j + " = " + i*j);
}
}
}
출력해보면 우리가 익히 알고있는 그 구구단표가 출력됩니다.
break문은 반복문을 하나 밖에 빠져나가지 못합니다.
public class BreakPoint {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=1; i<10; i++) {
for(int j=1; j<10; j++) {
System.out.println("[" + i + ", " + j + "]");
if(i%2==0 && j%2==0)
break;
}
}
}
}
public class LabeledBreak {
public static void main(String[] args) {
// TODO Auto-generated method stub
outerLoop :
for(int i=1; i<10; i++) {
for(int j=1; j<10; j++) {
System.out.println("[" + i + ", " + j + "]");
if(i%2==0 && j%2==0)
break outerLoop;
}
}
}
}
'Programming > JAVA' 카테고리의 다른 글
6-2 변수의 스코프 (0) | 2019.04.11 |
---|---|
6-1 메소드에 대한 이해와 메소드의 정의 (0) | 2019.04.02 |
5-4 continue & break (0) | 2019.03.09 |
5-3 for, while, do~while (0) | 2018.10.13 |
5-2 switch / break (0) | 2018.09.17 |