[JAVA] 2.조건문, 반복문

min·2024년 9월 10일

JAVA

목록 보기
3/10

조건문, 반복문도 문법이 C/C++과 같아서 빠르게 훑었다.

문법 익힐겸 작성해 본 예제 코드


import java.util.Scanner;

public class Test {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int input1, input2;
		
		System.out.print("input1? :");
		input1 = sc.nextInt();
		System.out.print("input2? : ");
		input2 = sc.nextInt();
		
		if((input1 % 2 == 0) && (input2 % 2 == 0)) {
			System.out.println("두 값 모두 짝수");
		}
		else {
			System.out.println("하나 이상 홀수");
		}

	}

}

input1? :15
input2? : 10
하나 이상 홀수


import java.util.Scanner;

public class Test {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int i, sum = 0;
		
		for(i = 0; i < 3; i++)
		{
			System.out.print("Score? : ");
			sum += sc.nextInt();
		}
		
		System.out.println("Sum : " +sum);
		System.out.println("Avg : " + sum / 3);

	}

}

Score? : 90
Score? : 85
Score? : 77
Sum : 252
Avg : 84

여기서 알게 된 새로운 문법은 사용자 입력 관련 코드.
java.util.Scanner 라는 라이브러리를 import 후, Scanner라는 클래스를 사용해서 입력 받는다.
그리고 따로 변수 선언해서 대입하지 않고 바로 사용할 수 있다.
관련해서는 추후 따로 정리해봐야겠다.

흐름 제어문

C/C++과 동일하게 break, continue 등 사용가능
label 이라는 개념이 등장함
중첩문을 끝내고 빠져나갈 수 있음

label : 실행문
...
break[continue] label

이런식으로 사용함

public class Test {

	public static void main(String[] args) {

		mylabel : for(int i = 0; i <3; i++)
		{
			System.out.println("Outer Loop : " + i);
			
			for(int j = 0; j < 3; j++)
			{
				System.out.println("--Inner Loop : " + j);
				if(j == 1) 
					break mylabel;
				
			}
		}
		
		
	}
}

Outer Loop : 0
--Inner Loop : 0
--Inner Loop : 1

j == 1 인 순간 중첩문을 빠져나와 프로그램이 끝남.
mylabel은 그냥 사용하고 싶은 이름 아무거나 사용하면 되는 듯.
C++에서 goto 개념이랑 비슷한 것 같은데, 나는 일하면서 goto를 거의 사용한 적이 없는데 JAVA에서는 잘 사용하는지 모르겠다.

public class Test {

	public static void main(String[] args) {

		mylabel : for(int i = 0; i <3; i++)
		{
			System.out.println("Outer Loop : " + i);
			
			for(int j = 0; j < 3; j++)
			{
				if(j == 1) 
					continue mylabel;
				
				System.out.println("--Inner Loop : " + j);
			}
		}
		
		
	}
}

Outer Loop : 0
--Inner Loop : 0
Outer Loop : 1
--Inner Loop : 0
Outer Loop : 2
--Inner Loop : 0

그냥 continue 였으면 Inner Loop 0과 2가 모두 출력 됐어야 했는데,
continue label이라 Inner Loop 0만 출력되고 넘어갔다.

0개의 댓글