관리 메뉴

거니의 velog

230711 자바 강의 본문

대덕인재개발원_Java

230711 자바 강의

Unlimited00 2023. 7. 12. 20:16

[ForExample01.java]

package ddit.chap04.sec02;

public class ForExample01 {

	public static void main(String[] args) {
		
//		forMethods01();
//		forMethods02();
//		forMethods03();
		forMethods04();
		
	}
	
	public static void forMethods01() {
		
		// 반복문 3가지의 수단, 목적이 다름.
		// 1. for : 반복 횟수를 정확하게 알고 있거나, 반복 횟수가 중요한 요소가 될 경우.
		//          제어변수(지역변수)를 이용해서 그 값을 판단해 반복을 할 것인지 말 것인지를 판단.
		
		// 1부터 10 사이의 수를 한 칸 공백을 두고 붙여서 출력하세요.
		
		for(int i=1; i<=10; i++) {
			
//			System.out.print(i + " "); // 1 2 3 4 5 6 7 8 9 10 
			
			// printf("형식지정문자열", 변수, 변수...)
			// "%[+,-][숫자] s(문자열)/f(실수)/d(10진수)"
			// printf("%3d %4s", s, n)
			
			// 숫자는 오른쪽 정렬, 문자는 왼쪽 정렬, 문자에 -가 붙으면 문자 취급되어 왼쪽 정렬.
			// printf("%d", i) 변수 길이를 지정하지 않으면 컴퓨터가 i의 길이를 보고 임의로 결정.
			
//			System.out.printf("%3d", i); //  1  2  3  4  5  6  7  8  9 10
			System.out.printf("%-2d", i); //1 2 3 4 5 6 7 8 9 10 // 
			
		}
		
	}
	
	public static void forMethods02() {
		
		// 알파벳 A~Z까지 한 줄에 출력하시오
//		for(char ch='A'; ch<='Z'; ch++) {
		for(int ch='A'; ch<='Z'; ch++) {
//			System.out.printf("%2c", ch); // A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
//			System.out.printf("%-2c", ch); //A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 
//			System.out.printf("%c", ch); //ABCDEFGHIJKLMNOPQRSTUVWXYZ
			System.out.print((char)ch); //ABCDEFGHIJKLMNOPQRSTUVWXYZ, 정수(아스키코드)를 문자로 변환한 경우
		}
		
	}
	
	public static void forMethods03() {
		
		// 0 ~ 50 사이의 fibonacci number(파보나치 수열) 값을 구하시오.
		// 피보나치 수열 : 1 번째와 2 번째 수가 1로 주어지고, 3번째 수부터 전 두수의 합이 현재 수가 되는 수열.
		// 1, 1, 2, 3, 5, 8, 13 ...
		int p = 1; // 전수(前數)
		int pp = 1; // 전전수(前前數)
		int current = 0; // 현재수
		
		System.out.printf("%-3d %-3d", p, pp);
		for(int i=0; i<51; i++) {
			current = p + pp;
			if(current >= 50) break;
			System.out.printf(" %-3d", current);
			pp=p;
			p=current;
		} // 1   1   2   3   5   8   13  21  34 
		
	}
	
	public static void forMethods04() {
		
		// 1 + 1/2 + 1/3 + ... + 1/10 = ?
		double sum = 0.0;
		for(int i=1; i<11; i++) {
			sum = sum + (1/(double)i);
		}
		System.out.printf("결과 = %7.2f", sum); // 지수부 4자리 + . + 가수부 2자리 = 총 7자리. 자동 반올림 가능.
		// 결과 =    2.93
		
	}

}

[NestedForExample.java]

package ddit.chap04.sec03;

public class NestedForExample {

	public static void main(String[] args) {
		
//		nestedForMethod01();
		nestedForMethod02();
		
	}
	
	public static void nestedForMethod01() {
		
		// 1부터 10까지의 수를 붙여서 5줄 인쇄하시오.
		for(int i=0; i<5; i++) { // 바깥쪽 for문. 줄을 담당
			for(int j=0; j<10; j++) {
				System.out.print(j+1);
			}
			System.out.println(); // 줄바꿈
		}
		
	}
	
	public static void nestedForMethod02() {
		
		// 2단~9단까지 구구단을 출력
		// 단수는 잘 변하지 않는 수 이므로 바깥 for
		// 곱하는 수(승수)는 1~9까지 끊임없이 변하므로 안쪽 for
		for(int i=2; i<10; i++) {
			System.out.println("[[" + i + "단]]");
			for(int j=1; j<10; j++) {
				System.out.println(i + " * " + j + " = " + (i*j));
			}
			System.out.println();
		}
		
	}

}

[NestedForExample02.java]

package ddit.chap04.sec03;

public class NestedForExample02 {

	public static void main(String[] args) {
		
//		nestedForMethod01();
//		nestedForMethod02();
//		nestedForMethod03();
		nestedForMethod04();
		
	}
	
	public static void nestedForMethod01() {
		for(int i=0; i<5; i++) {
			for(int j=0; j<=i; j++) {
				System.out.print("*"); // "*"출력
			}
			System.out.println();
		}
	}
	
	public static void nestedForMethod02() {
		for(int i=0; i<5; i++) {
			for(int j=0; j<4-i; j++) {
				System.out.print(" "); // 공백출력
			}
			for(int j=0; j<=i; j++) {
				System.out.print("*"); // "*"출력
			}
			System.out.println(); // 줄바꿈
		}
	}
	
	public static void nestedForMethod03() {
		for(int i=0; i<5; i++) {
			for(int j=0; j<5-i; j++) {
				System.out.print("*"); // "*"출력
			}
			System.out.println();
		}
	}
	
	public static void nestedForMethod04() {
		for(int i=0; i<5; i++) {
			for(int j=0; j<i; j++){
				System.out.print(" "); // 공백출력
			}
			for(int j=0; j<5-i; j++) {
				System.out.print("*"); // "*"출력
			}
			System.out.println();
		}
	}

}

[WhileExample.java]

package ddit.chap04.sec04;

import java.io.IOException;
import java.util.Scanner;

public class WhileExample {

	// 코치 클래스(마부 클래스)
	public static void main(String[] args) {

		try {
			WhileStatement ws = new WhileStatement(); // 생성자(Instructor). 클래스의 초기화를 담당.
//			ws.whileMethod01();
//			ws.whileMethod02();
			ws.whileMethod03();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

// 워크호스(일하는 말) 클래스
class WhileStatement {

	public void whileMethod01() {
		// 1-100 사이의 홀수와 짝수의 합을 구하시오.

		int cnt = 1; // 1~100 사이의 값을 보관
		int odd = 0; // 홀수의 합
		int even = 0; // 짝수의 합

		while (cnt <= 100) {
			if (cnt % 2 == 0) {
				even += cnt;
			} else {
				odd += cnt;
			}
			cnt++;
		}

		System.out.println("홀수의 합 : " + odd);
		System.out.println("짝수의 합 : " + even);
	}

	public void whileMethod02() {
		// 키보드로 숫자 하나를 입력 받아 각 자리수의 합을 구하시오
		// ex) 23456 => 2+3+4+5+6 = 20;

		Scanner sc = new Scanner(System.in);
		System.out.print("숫자 입력 : ");

		int num = sc.nextInt();
		int sum = 0;

		while (num != 0) {
			sum = sum + (num % 10); // 나머지를 구하여 sum에 계속 더함.
			num = num / 10; // 몫을 구하여 num = 0이 될 때까지 반복함.
		}

		System.out.println("각 자리수의 합은 " + sum + " 입니다.");

		sc.close();
	}

	public void whileMethod03() throws IOException {
		
		// 컴퓨터가 1-50사이의 난수를 하나 발생시키고
		// 사용자가 그 숫자를 맞추는 게임.
		// 컴퓨터 난수 > 사용자 입력 숫자 => "더 큰 수 입력"
		// 컴퓨터 난수 < 사용자 입력 숫자 => "더 작은 수 입력"
		// 컴퓨터 난수 = 사용자 입력 숫자 => "정답입니다" 출력후 시도횟수까지 출력.
		
		Scanner sc = new Scanner(System.in);

		int randomNum = (int) (Math.random() * 50) + 1; // 1~50 사이의 무작위 정수
		int answer = 0; // 사용자 입력 정수
		int cnt = 0; // 시도 횟수
		int ch = 0; // 계속 진행할 것인지 여부

		do {
			System.out.print("숫자입력(1~50) : ");
			
			cnt = 0; // 시도 횟수 초기화
			randomNum = (int) (Math.random() * 50) + 1; // 무작위 정수 초기화
			
			answer = sc.nextInt(); // 사용자 정수값을 입력받아 answer에 저장
			cnt++; // 시도 횟수 1 증가
			
			while (true) {
				if (answer == randomNum) {
					System.out.println("정답입니다.");
					System.out.println("시도횟수 : " + cnt);
					break;
				} else if (answer > randomNum) {
					System.out.print("더 작은 수를 입력하세요 : ");
				} else if (answer < randomNum) {
					System.out.print("더 큰 수를 입력하세요 : ");
				}
				answer = sc.nextInt();
				cnt++;
			}
			System.out.print("계속하겠습니까?(y/n) : ");
		}while ((char) (ch = System.in.read()) == 'y');
		
		sc.close();

	}

}

[NestedForHomework.java]

package ddit.chap04.sec03;

public class NestedForHomework {

	public static void main(String[] args) {
		
//		nestedForMethod05();
//		nestedForMethod06();
		nestedForMethod07();
		
	}
	
	public static void nestedForMethod05() {
		
		for(int i=0; i<5; i++) {
			for(int j=0; j<4-i; j++) {
				System.out.print(" ");
			}
			for(int j=0; j<=i; j++) {
				System.out.print("*"); // "*"출력
			}
			for(int j=1; j<=i; j++) {
				System.out.print("*"); // "*"출력
			}
			System.out.println();
		}
		
	}
	
	public static void nestedForMethod06() {
		
		for(int i=0; i<5; i++) {
			for(int j=1; j<=i; j++) {
				System.out.print(" ");
			}
			for(int j=0; j<=4-i; j++) {
				System.out.print("*"); // "*"출력
			}
			for(int j=1; j<=4-i; j++) {
				System.out.print("*"); // "*"출력
			}
			System.out.println();
		}
		
	}
	
	public static void nestedForMethod07() {
		
		for(int i=0; i<5; i++) {
			for(int j=0; j<4-i; j++) {
				System.out.print(" ");
			}
			for(int j=0; j<=i; j++) {
				System.out.print("*"); // "*"출력
			}
			for(int j=1; j<=i; j++) {
				System.out.print("*"); // "*"출력
			}
			System.out.println();
		}
		
		for(int i=0; i<5; i++) {
			for(int j=0; j<=i; j++) {
				System.out.print(" ");
			}
			for(int j=0; j<=3-i; j++) {
				System.out.print("*"); // "*"출력
			}
			for(int j=1; j<=3-i; j++) {
				System.out.print("*"); // "*"출력
			}
			System.out.println();
		}
		
	}

}

'대덕인재개발원_Java' 카테고리의 다른 글

230713 자바 강의  (0) 2023.07.13
230712 자바 강의  (0) 2023.07.12
230710 자바 강의  (0) 2023.07.12
230707 자바 강의  (0) 2023.07.12
230706 자바 강의  (0) 2023.07.12