국비교육 2주일차 java 복습 1 (1/24~1/27)

2022. 2. 6. 23:57SW개발 (22.01~)/java (22.01~)

220124

package day0124;

public class WhileTrueScan_02 
		/*
		 * 합계를 구할 숫자를 입력하시오
		 * 10
		 * 1~10까지의 합: 55
		 * 
		 * for과 while(true)로 각각 작성할것 
		 */
         
public class WhileTrueCnt_03
		/*
		 * 3의 배수 개수 : 33개
		 *
		 * 1~100까지의 숫자중에서 3의 배수는 총 몇개가 있는지 개수를 구하시오 
		 * while(true)로 구할것
		 */
         
public class QuizForContinue_09
		/*
		 * 총 5개의 점수를 입력받아서 합계를 구한다.(반복문에서 입력하기) 
		 * 만약 1~100이 아닐 경우 다시 입력받으시오(continue 사용)
		 * 반복문에서 잘못 입력한 것은 빼기 
		 * for문 안에 if문 (반복문 안에 제어문) 
		 * 1번점수:88 
		 * 2번점수:-77 
		 * 잘못입력했어요 
		 * 2번점수:99
		 * ... 
		 * 5번점수:55 
		 * 총점:***
		 */
         
public class ForGuguBreak_14
		/*
		 * 2~9단까지를 출력하되 각각 4까지만 출력되게 하시오 
		 * break를 이용하시오
		 */
         
public class QuixWhileTrueGugu_16 
		/*
		 * while(true) 0이라고 입력시 종료 단은 2~9단까지만 입력할 것 (continue 이용)
		 * 
		 * 단을 입력하시오(종료:0) --> 5 
		 * [5단] 5X1=5 ...
		 * 0 입력시 프로그램을 종료합니다
		 */

구구단

public class ForGuguEx_13 {

	public static void main(String[] args) {
		for (int i=2;i<=9;i++) {
			for(int j=1;j<=9;j++) {
				System.out.println(i+"X"+j+"="+i*j);
			}
			System.out.println();
		}
	}

}

반복문에 이름주기

public class ForBreakLoop_15 {

	public static void main(String[] args) {

		loop1: for (int i = 2; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				if (j == 5)
					break loop1; // name을 줌으로써 먼곳의 반복문도 빠져나갈 수 있다.
				System.out.println(i + "X" + j + "=" + i * j);
			}
			System.out.println();

		}

	}

}

220125

package day0125;

public class ForWhileReview_01
	public static void ScanSum_05()
		// for, continue
		// 세번째 점수까지 입력하면 합계 출력
		// 0~100사이가 아니면 잘못된 점수입니다 나오고 횟수 차감
		// 1번째 점수를 입력하세요(0~100)
		// 총합계 : **
        
public class ForWhileReview_02         
        public static void scanFactorialEx_01()
		// 숫자를 입력시 팩토리얼 값을 출력하기
		// 5입력시 5!=120
        
        public static void scanStringTextEx_02()
		// String class에서 equals, startsWith 사용
		// 이름입력 (종료=끝) 
        	// 이름을 반복해서 입력후 김씨가 몇명인지 알아볼것
     	  	 // "김씨성을 가진 사람은 ***명입니다"
             
public class RandomSuMatch_04 
		/*
		 * 여러회차에 걸쳐서 난수 알아맞히기 
		 * 1회: 맞힐 수를 입력하세요>  77 
		 * 77보다 작습니다 
		 * 2회: 맞힐 수를 입력하세요> 55 
		 * 55보다 큽니다 
		 * 3회: 맞힐 수를 입력하세요> 66 
		 * 맞아요~ 정답은 66입니다
		 * 프로그램을 종료합니다
		 */
         
public class QuizOperEx_05
	public static void ex_01()
		// for문으로 10번 질문할 것 (0은 세지 않는다)
		// 1: 0
		// 2: -23
		// ...
		// 10: 88
		// =================
		// 양수개수: 4
		// 음수개수: 5
        public static void ex_02() {
		/*
		 * while(true)문 이용할 것
		 * continue를 이용하여 1~100까지의 짝수의 합을 구하시오
		 * 1~100까지의 짝수의 합 : ****
		 */
         
         public static void ex_04() {
		/*
		 * while(true)을 이용할것
		 * 1~10까지 팩토리얼 구할것
		 * 
		 * 1!=****
		 * ...
		 * 9!=****
		 * 10!=****
		 */
         
public class ForGuguEx_06 
	public static void height_gugu()
		// [2단]
		// 2X1=2
		// 2X2=4
		// ...
		// 2단부터 9단까지 아래방향으로 출력

	public static void width_gugu()
		// [2단]	[3단]
		// 2X1=2	3X1=3
		// 2X2=4	3X2=6
		// ...
		// 2단부터 9단까지 가로방향으로 출력

난수발생 공식

int n =(int)(Math.random()*m)+n;

-->> n~(m+n-1)

===========================================================================

220126

 

 

for문, for~each문

public class ArraysEx_02 {

	public static void main(String[] args) {
		// 배열선언
		// 기본형배열은 객체로 인식

		// int [] arr = new int[3]; //메모리 할당
		// int arr [] = new int[3]; //할당만 하더라도 값을 주지 않더라도 0으로 초기화된다
		// 선언과 동시에 초기값을 주기도 한다

		// 배열선언
		int[] arr;
		arr = new int[3];

		// 배열에 값넣기
		arr[0] = 10;
		arr[1] = 5;
		arr[2] = 20;

		System.out.println("arr 배열의 개수: " + arr.length);

		// 출력시 반복문을 이용해서 일괄적으로 출력
		System.out.println("***arr for문으로 일괄출력***");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}

		System.out.println("***arr for~each문으로 일괄출력***");
		for (int i : arr) { // for~each(같은 자료형인 참조변수명:배열명)
			System.out.println(i);
		}
        }

}
public class QuizSawon_02 {

	public static void writeSawon(Sawon s) {
		System.out.println(s.getName() + "\t" + s.getPay() + "\t" + s.getSudang() + "\t" + s.getTotalPay());

	}

	public static void main(String[] args) {
        for (int i = 0; i < sw.length; i++)
		writeSawon(sw[i]);
		
	for (Sawon s:sw)
		writeSawon(s);
        }

}

최소값과 최대값 구하기

public class ArraysMaxMinEx_06 {

	public static void main(String[] args) {

		int[] data = { 5, 12, 66, 88, 98, 100, 35, 67, 54, 18 };
		System.out.println("개수: " + data.length);

		int max = data[0]; // 배열에서는 첫데이터를 무조건 최대값에 저장
		int min = data[0]; // 다음 값과 비교하는 구조

		// 두번째 데이터부터 끝까지 max와 비교
		for (int i = 1; i < data.length; i++) {
			if (max < data[i])
				max = data[i];
			if (min > data[i])
				min = data[i];
		}
		System.out.println("최대값: "+max);
		System.out.println("최소값: "+min);

	}

}

 

문제

package day0126;

public class ArraysScanEx_05
// 배열의 범위만큼 입력후 출력해보자
// 입력 후 출력시 입력한 숫자의 합을 구해보세요
1번째 값: 33
2번째 값: 44
3번째 값: 55
4번째 값: 66
5번째 값: 77
입력값 확인
0==>33
1==>44
2==>55
3==>66
4==>77
총합계: 275

public class ArraysScanChange_07
인원 수를 입력하세요 3
1번째 학생명: ㅇㅇ
1번째 학생 점수: 33
2번째 학생명: ㅁㅁ
2번째 학생 점수: 55
3번째 학생명: ㅅㅅ
3번째 학생 점수: 77
번호 이름 점수
=================================
1 ㅇㅇ 33 3
2 ㅁㅁ 55 2
3 ㅅㅅ 77 1
=================================
총점:  165
평균:  55.0

public class ArraysIntSearchEx_08
		/*
		 * 스캐너로 숫자를 입력받아서 배열의 몇번째 있는지 출력하세요
		 * 없을경우 없다고 출력하세요..0을 입력시 종료하세요
		 */

검색할 숫자 입력
56
56는 데이터에 없습니다
검색할 숫자 입력
88
5번째에서 검색
검색할 숫자 입력
0

public class RankReview_09
		/*
		 * 각 학생들의 점수에 대한 총점, 평균, 등수를 구하여 출력
		 * 번호 이름 자바 오라클 총점 평균 등수
		 */
		
public class ArraysStringSearchEx_10
		/*
		 * "검색할 이름을 입력하세요" 이름을 입력해서 그 이름이 몇번째에 있는지 출력 
		 * 있으면 "해당 이름은 n번째에 있습니다" 라고 출력 
		 * 없으면 "해당 이름은 데이터에 없습니다" 라고 출력
		 * 끝이라고 입력하면 "검색을 종료합니다" 출력 후 종료
		 * 
		 * Scanner, While(true),boolean을 사용
		 */

 

=======================================================================

220127

문제

package day0127;


import java.util.Arrays;

public class ArraysTempEx_03 
		int[] arr = { 5, 7, 3, 9, 12, 45, 76, 89, 10 };
        // 거꾸로 데이터를 바꾸어 출력
        // 그 뒤에 오름차순 출력 (중첩 for문, Arrays이용하여 각각)


public class ArraysSortEx_05

		String[] name = {"이효리", "강호동", "김태희", "유재석", "하하"};
		int[] age = {39,45,33,38,32};
		/*
		 * 번호	이름	나이
		 * 1	강호동	45
		 * 
		 * 이름의 오름차순으로 출력
		 */
         
public class ArraysDdi_06 
	
	/*
	 * 이름 입력
	 * 홍길동
	 * 태어난 년도 입력
	 * 1997
	 * 홍길동님은 소띠입니다
	 * 
	 * Scanner
	 * String[] ddi, String name, int myYear, String myDdi
	 */
     
     
package day0128;

public class ArraysLottoReview_01

로또 구입 금액을 입력해주세요 500
금액이 부족합니다

========================================================================

로또 구입 금액을 입력해주세요 3000
  1회:    19   20   21   30   37   45
  2회:    11   18   26   29   39   45
  3회:     1    4    6   18   22   41

로또

public class LottoEx_07 {

	public static void main(String[] args) {
		// 로또를 출력해보자. 중복된 번호 없어야하고, 오름차순 정렬

		int[] lotto = new int[6];

		// 임의의 수를 로또변수에 발생시켜서 넣어준다

		for (int i = 0; i < lotto.length; i++) {
			lotto[i] = (int) (Math.random() * 45) + 1; // 1~45 사이 랜덤수
			System.out.println("뽑은 값 "+(i+1)+": "+ lotto[i]);

			// 중복처리
			// 중복제거 : 현재index(i)와 (0~i-1) 비교해서 중복된 숫자 존재시 i--
			for (int j = 0; j < i; j++) {
				// 조건문
				if (lotto[i] == lotto[j]) {
					System.out.println(lotto[i] + "==" + lotto[j]);
					System.out.println("중복");
					i--; // 같은번지에 다시 값을 구하기 위해서
					break;
				}
			}
		}
		
		//오름차순 정렬
		// Arrays.sort(lotto);
		for (int i=0;i<lotto.length-1;i++) {
			for (int j=i+1;j<lotto.length;j++) {
				if(lotto[i]>lotto[j]) {
					int temp = lotto[i];
					lotto[i]=lotto[j];
					lotto[j]=temp;
				}
			}
		}
		
		// 출력
		for (int i = 0; i < lotto.length; i++) {
			System.out.print(lotto[i] + "\t");
		}

	}

}

뽑은 값 1: 36
뽑은 값 2: 32
뽑은 값 3: 15
뽑은 값 4: 36
36=36
중복
뽑은 값 4: 7
뽑은 값 5: 14
뽑은 값 6: 28
7 14 15 28 32 36

 

빙고

import java.util.Scanner;

public class ArraysBingoEx_10 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int[][] pz = new int[3][3];
		int bingo = 0;

		while (true) {
			System.out.println("**같은 숫자가 나오면 빙고!!**");

			// 1~3 사이의 난수 발생
			for (int i = 0; i < pz.length; i++) {
				for (int j = 0; j < pz[1].length; j++) {
					pz[i][j] = (int) (Math.random() * 3) + 1;
				}
			}

			// 출력
			for (int i = 0; i < pz.length; i++) {
				for (int j = 0; j < pz[i].length; j++) {
					System.out.printf("%4d", pz[i][j]);
				}
				System.out.println();
			}

			// 빙고 조건
			// 가로방향 3개, 세로방향 3개
			for (int i = 0; i < pz.length; i++) {
				// 가로방향 비교
				if (pz[i][0] == pz[i][1] && pz[i][1] == pz[i][2])
					bingo++;
				// 세로방향 비교
				if (pz[0][i] == pz[1][i] && pz[1][i] == pz[2][i])
					bingo++;
			}

			// 대각선방향 /
			if (pz[0][2] == pz[1][1] && pz[1][1] == pz[2][0])
				bingo++;

			// 대각선방향 \
			if (pz[0][0] == pz[1][1] && pz[1][1] == pz[2][2])
				bingo++;

			// 빙고 출력
			if (bingo == 0)
				System.out.println("\t꽝!");
			else {
				System.out.println("\t빙고"+bingo+"개");
				bingo = 0;
			}
			
			System.out.println("엔터를 누르면 다음 난수가 발생합니다(종료Q)");
			String ent = sc.nextLine();
			
			if(ent.equalsIgnoreCase("q")) {
				System.out.println("게임을 종료합니다");
				break;
			}
		}

	}

}

**같은 숫자가 나오면 빙고!!**
   1   2   1
   1   3   2
   1   1   1
빙고2개
엔터를 누르면 다음 난수가 발생합니다(종료Q)