본문 바로가기
Programming Language/Java

[국비] Java 내용정리 Day04

by tpleehan 2021. 10. 29.

삼항 연산자

  • 피 연산자(연산을 당하는 값)가 3개인 연산자를 말한다.
    • 삼항 연산식 : (조건식 ? 좌항 : 우항)
  • 조건식을 비교하여 true가 도출되었을 시 좌항의 값이 도출되고, false가 도출되었을 시 우항의 식이 도출된다.
public class ConOperator {
	public static void main(String[] args) {

		int x = 10, y = 20;

		String result = (x > y ? "x는 y보다 크다." : "x는 y보다 작다.");
		System.out.println(result);

		//난수를 발생시키는 메서드 Math.random();//0.0이상 1.0미만의 실수 난수값을 반환합니다.

//		double rn = Math.random();//		System.out.println(rn);

		//1~10까지의 정수 난수 구하기int rn = (int) ((Math.random() * 10) + 1);
		System.out.println(rn);

		//10 ~ 100까지의 정수 난수를 구하기int rn2 = (int) ((Math.random() * 91) + 10);
		System.out.println(rn2);

		//34 ~ 176까지의 정수 난수를 구하기int rn3 = (int) ((Math.random() * 143) + 34);
		System.out.println(rn3);

		//27 ~ 232까지의 정수 난수를 구하기int rn4 = (int) ((Math.random() * 206) + 27);
		System.out.println(rn4);
	}
}

Conditional Operator Quiz01

문제)
42 ~ 396 사이의 난수를 발생시킨다.
발생한 난수가 홀수인지 짝수인지의 여부를 3항 연산식으로 출력한다.

예시)
발생한 난수 : XX 3항 연산의 결과: 홀수입니다. or 짝수입니다.

public class ConOperatorQuiz {
	public static void main(String[] args) {
		
		int rn = (int) ((Math.random() * 355) + 42);
		System.out.println("발생한 난수: " + rn);
		
		String result = (rn % 2 == 1 ? "홀수입니다." : "짝수입니다.");
//		String result = (rn % 2 == 0 ? "짝수입니다." : "홀수입니다.");
//		System.out.println("3항 연산의 결과: " + (rn % 2 == 1 ? "홀수입니다." : "짝수입니다."));
		
		System.out.println("3항 연산의 결과: " + result);		
	}
}​

반복문 While

  • while문은 조건식을 검사하여 참일 경우 블록 내부의 코드를 실행하며 실행이 끝날 때마다 반복적으로 조건식을 검사하여 false가 나올 때까지 반복한다.
  • while문도 if와 마찬가지로 논리값이 도출되는 조건식이나 함수를 사용한다.
  • while문은 반복 횟수를 제어하기 위한 증감식이나 탈출문이 필요하다.
public class WhileExample1 {
	public static void main(String[] args) {

		int n = 1;//제어변수: 반복문의 횟수를 제어할 변수. (begin)

		while (n <= 10) {//논리형 조건식: 반복문의 끝을 지정. (end)
			System.out.println("안녕하세요. 반갑습니다.");
			n++;//증감식: 반복문의 종료를 위해 제어변수의 값을 조정. (step)
		}

		System.out.println("-------------------------------------");

		//1 ~ 10의 누적합을 구하는 로직
        int i = 1; //begin
        int total = 0; //누적합을 기억해줄 변수

		while (i <= 10) {
			total += i;
			i++;//step
		}

		System.out.println("1 ~ 10의 누적합: " + total);
	}
}
while문의 진행 순서
1. 제어변수를 선언한다. (시작 값이 정해짐)
2. 조건식을 검사해서 true면 반복문이 진행한다.
    false가 되면 반복문 종료한다.
3. while문 블록 내부가 한 번 진행되면, 다시 조건식을 검사하여 true면 반복문이 계속 진행한다.
    false가 되면 반복문 종료.
4. 반복문 내에는 증감식을 배치해서 제어 변수의 값을 조정한다.
public class WhileExample2 {
	public static void main(String[] args) {
		
		//48 ~ 150사이의 정수 중 8의 배수만 가로로 출력하라.
		//48부터 숫자를 하나씩 올려가면서 8의 배수를 판복 반복		
		int n = 48;
		
		while (n <= 150) {
			if(n % 8 == 0) {
				System.out.print(n + " ");
			}
			//System.out.print(n % 8 == 0 ? n + " ": "");
			
			n++;

		}
		 
		System.out.println(); //단순 줄 개행
		//1 ~ 100까지의 정수 중 4의 배수이면서
		//8의 배수는 아닌 수를 가로로 출력		
		int i = 1;
		
		while (i <= 100) {
			if (i % 4 == 0 && i % 8 != 0) {
				System.out.print(i + " ");
			}
			
//			if (i % 4 == 0) {
//				if (i % 8 != 0) {
//					System.out.print(i + " ");
//				}
//			}
			
			i++;

		}
		
		System.out.println();
		
		//1~30000까지의 정수 중 258의 배수의 개수를 출력.		
		int j = 1;
		int count = 0; //배수의 개수를 기억해 줄 변수.
		
		while (j <= 30000) {			
			if (j % 258 == 0) {
				count++;
			}

			j++;
		}
		System.out.println("1~30000중의 258의 배수의 개수: " + count + "개");
		
		//1000의 약수의 개수를 구하라.
		//1부터 1000까지 하나씩 올려가면서 1000이랑 나누고
		//나누어 떨어진 값이 약수이다.		
		int k = 1;
		int cnt = 0;
		
		while (k <= 1000) {			
			if (1000 % k == 0) {
				cnt++;
			}
			
			k++;
		}
		System.out.println("1000의 약수의 개수: " + cnt + "개");
		
	}
}

While Quiz01

문제)
사용자에게 구구단 단수를 입력 받아서 해당 단수의 구구단을 출력한다.

예시)
구구단을 입력하세요 : 4

*** 구구단 4 단 ***
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
...
4 x 9 = 36
import java.util.Scanner;

public class WhileQuiz01 {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.print("구구단을 입력하세요 : ");
		int dan = sc.nextInt();
		System.out.println("*** 구구단 " + dan + "단 ***");

		int hang = 1;

		while(hang <= 9) {
//			System.out.printf("%d x %d = %d\n", dan, hang, dan * hang);
			System.out.println(dan + " x " + hang + " = " + dan * hang);

			hang++;

		}

		sc.close();
	}
}​

While Quiz02

문제)
입력 받은 수의 약수의 총합을 구한다.

예시)
입력 받은 값: 12 -> 1 2 3 4 5 6 12 -> 28
import java.util.Scanner;

public class WhileQuiz02 {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.print("정수를 입력하세요: ");
		int num = sc.nextInt();

		int i = 1;// beginint total = 0;//누적합을 담을 변수

		while (i <= num) {
			if (num % i == 0) {
				total += i;
			}
			i++;

		}
		System.out.println("입력받은 값: " + num + " -> " + total);

		sc.close();
	}
}​
import java.util.Scanner;

public class WhileExample3 {
	public static void main(String[] args) {

		/*
		 - 정수 1개를 입력 받아 해당 정수가 소수(prime number)인지 판별
		 */

		Scanner sc = new Scanner(System.in);

		System.out.print("정수를 입력하세요: ");
		int num = sc.nextInt();

		int i = 1; //소수의 판별을 위해 입력받은 정수 num을 지속적으로 나눌 변수
        int count = 0; //나누어 떨어진 횟수를 기억할 변수

		while (i <= num) {
			if (num % i == 0) {
				count++;
			}
			i++;
		}

		if (count == 2) {
			System.out.println(num + " 은(는) 소수입니다.");
		} else {
			System.out.println(num + " 은(는) 소수가 아닙니다.");
		}

		System.out.println("------------------------");

		int j = 2;//1은 모든 수의 약수이기 때문에 배제

		while (num % j != 0) {
			j++;
		}

		System.out.println(num == j ? "소수입니다." : "소수가 아닙니다.");

		sc.close();

	}
}

While Quiz03

문제)
1. 정수를 두개 입력받는다. (x, y)
2. x부터 y까지의 누적합계를 while을 사용하여 구하는 코드 작성

예시)
ex) 입력 3, 7 -> "3부터 7까지의 누적합계: 25"

Hint)
처음에는 x에 무조건 작은 값을 들어올 것이라고 예상하고 작성한다.
완료 후 x에 큰 값이 들어왔을 경우 어떻게 대처할지 생각하라.
(x에 큰 값이 들어와도 정삭적으로 출력이 되어야 한다. 입력: 7, 3 -> "3부터 7까지의 누적합계: 25")
※ while문을 if else 로 나눠서 두 번 쓰는 것을 지양
import java.util.Scanner;

public class WhileQuiz03 {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.print("첫 번째 정수를 입력하세요: ");
		int num1 = sc.nextInt();

		System.out.print("두 번째 정수를 입력하세요: ");
		int num2 = sc.nextInt();

		if (num1 > num2) {
			int temp = num2;
			num2 = num1;
			num1 = temp;
		}

		int total = 0;

		int start = num1;

		while (start <= num2) {
			total += start;
			start++;

		}

		System.out.println(num1 + "부터 " + num2 +  "까지의 누적합계: " + total);

		sc.close();
	}
}​

반복문 for

  • for문은 반복제어조건을 한꺼번에 지정한다는 점이 다른 반복문과 다르다.
  • 정확한 반복 횟수를 알고 있을 경우 for문이 while문보다 효율적이다.
import java.util.Scanner;

public class ForExample {
	public static void main(String[] args) {

		/*
		int i = 1;
		int total = 0;

		while(i <= 10) {
			total += i;
			i++;
		}
		System.out.println(total);
		 */

		int total = 0;
		for (int i = 1; i <= 10; i++) {
			total += i;
		}

		//1~200까지의 정수 중 6의 배수이면서 12의 배수는 아닌 수를 가로로 출력 (for)

		for (int i = 1; i <= 200; i++) {
			if(i % 6 == 0 && i % 12 != 0) {
				System.out.print(i + " ");
			}
		}

		System.out.println();

		//1~60000까지의 정수 중 177의 배수의 개수를 출력 (for)int count = 0;

		for (int i = 1; i <= 60000; i++) {
			if(i % 177 == 0) {
				count++;
			}
		}
		System.out.print("1~60000 중 177의 배수의 개수: " + count + "개");

		System.out.println();

		//입력 받은 정수까지의 팩토리얼 값을 구하라.//팩토리얼) 5! -> 5 x 4 x 3 x 2 x 1
		Scanner sc = new Scanner(System.in);

		System.out.print("정수 입력: ");
		int num = sc.nextInt();

		int fac = 1;//팩토리얼 최종 결과를 담을 변수

		for (int i = 1; i <= num;  i++) {
			fac = fac * i;
		}

//		for (int i = num; i >= 1; i--) {//			fac *= i;//		}

		System.out.println(num + "! -> " + fac);

		sc.close();
	}
}

for Quiz01

문제)
2~19까지의 난수를 생성하여 구구단을 출력 (for)
19행까지 출력
public class ForQuiz01 {
	public static void main(String[] args) {

		int dan = (int) ((Math.random() * 18) + 2);

		for(int hang = 1; hang <= 19; hang++) {
			System.out.println(dan + " x " + hang + " = " + dan * hang);
		}
	}
}​

'Programming Language > Java' 카테고리의 다른 글

[국비] Java 내용정리 Day06  (0) 2021.11.01
[국비] Java 내용정리 Day05  (0) 2021.10.29
[국비] Java 내용정리 Day03  (0) 2021.10.28
[국비] Java 내용정리 Day02  (0) 2021.10.26
[국비] Java 내용정리 Day01  (0) 2021.10.25

댓글