✅ 문제

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

public class Ex_0629_02 {
    public static void main(String[] args) throws IOException {
        //문제 7 : 다음 각 절차를 따라 작성하시오.
        //// 1. res/map.txt 파일을 생성하고 다음 데이터를 복사/붙여넣으시오.
        //
        //00010
        //01010
        //00000
        //// 2. map이라는 이름으로 5x3 크기의 정수를 담을 수 있는 이차원 배열과 board라는 이름의 10X6크기의 문자를 담을 수 있는 이차원 배열을 생성하시오.
        //
        //[           ]  map = [                                      ];
        //[           ]  board = [                                      ];

        int[][] map = new int[3][5];
        char[][] board = new char[6][10];

        {
            FileInputStream fis = new FileInputStream("afterschool/res/map.txt");
            Scanner fscan = new Scanner(fis);

            for (int i = 0; i < map.length; i++) {
                String str = fscan.nextLine();
                for (int j = 0; j < map[i].length; j++) {
                    String[] tokens = str.split("");
                    map[i][j] = Integer.parseInt(tokens[j]);
                }
            }
        }
        System.out.println("map 데이터 로드 완료");
        //// 3. res/map.txt에서 읽은 데이터로 map 배열을 채우시오.
        //
        //{
        //    // 코드를 작성하는 공간
        //
        //    System.out.println(“map 데이터 로드 완료”);
        //}



        //// 4. map 데이터 하나는 board 배열의 4칸과 대응되며 다음과 같은 모양으로 대응된다.
        //// map에서 0은 다음 모양과 같다.
        //// ┌ ┐
        //// └ ┘
        //// map에서 1은 다음 모양과 같다.
        //// ▩▩
        //// ▩▩
        //// map에서 읽은 데이터를 이용해서 board 배열을 채우시오.  다음은 board 배열에 채워진
        //// 모습니다.
        //// ┌ ┐┌ ┐┌ ┐▩▩┌ ┐
        //// └ ┘└ ┘└ ┘▩▩└ ┘
        //// ┌ ┐▩▩┌ ┐▩▩┌ ┐
        //// └ ┘▩▩└ ┘▩▩└ ┘
        //// ┌ ┐┌ ┐┌ ┐┌ ┐┌ ┐
        //// └ ┘└ ┘└ ┘└ ┘└ ┘
        //
        //{
        //     // 코드를 작성하는 공간
        //
        //
        //
        //    System.out.println(“board 그리기 완료”);
        //}

        //보드 윤곽 넣기
        {
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 10; j++) {
                    if ((i % 2 == 0))
                        if (j % 2 == 0)
                            board[i][j] = '┌';
                        else
                            board[i][j] = '┐';
                    else if (j % 2 == 0)
                        board[i][j] = '└';
                    else
                        board[i][j] = '┘';
                }
                System.out.println();
            }
        }

        //이상한 네모 입력
        {
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 5; j++) {
                    if (map[i][j] == 1) {
                        int row = i * 2;
                        int col = j * 2;
                        board[row][col] = '▩';
                        board[row][col + 1] = '▩';
                        board[row + 1][col] = '▩';
                        board[row + 1][col + 1] = '▩';
                    }
                }
        }

        //출력
        {
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 10; j++) {

                    System.out.printf("%c", board[i][j]);
                }
                System.out.println();
            }
        }


        //// 5. board 배열을 화면에 출력하는 코드를 작성하시오.
        //
        //{
        //     // 코드를 작성하는 공간
        //
        //
        //
        //    System.out.println(“board 출력 완료”);
        //}
    }
}

✅ 해결방법

  • for문으로 좌표를 뽑아두고 규칙을 찾으면 편하다.


✅ 코드

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

public class Ex_0629_02 {
    public static void main(String[] args) throws IOException {
        //문제 7 : 다음 각 절차를 따라 작성하시오.
        //// 1. res/map.txt 파일을 생성하고 다음 데이터를 복사/붙여넣으시오.
        //
        //00010
        //01010
        //00000
        //// 2. map이라는 이름으로 5x3 크기의 정수를 담을 수 있는 이차원 배열과 board라는 이름의 10X6크기의 문자를 담을 수 있는 이차원 배열을 생성하시오.
        //
        //[           ]  map = [                                      ];
        //[           ]  board = [                                      ];

        int[][] map = new int[3][5];
        char[][] board = new char[6][10];

        {
            FileInputStream fis = new FileInputStream("afterschool/res/map.txt");
            Scanner fscan = new Scanner(fis);

            for (int i = 0; i < map.length; i++) {
                String str = fscan.nextLine();
                for (int j = 0; j < map[i].length; j++) {
                    String[] tokens = str.split("");
                    map[i][j] = Integer.parseInt(tokens[j]);
                }
            }
        }
        System.out.println("map 데이터 로드 완료");
        //// 3. res/map.txt에서 읽은 데이터로 map 배열을 채우시오.
        //
        //{
        //    // 코드를 작성하는 공간
        //
        //    System.out.println(“map 데이터 로드 완료”);
        //}



        //// 4. map 데이터 하나는 board 배열의 4칸과 대응되며 다음과 같은 모양으로 대응된다.
        //// map에서 0은 다음 모양과 같다.
        //// ┌ ┐
        //// └ ┘
        //// map에서 1은 다음 모양과 같다.
        //// ▩▩
        //// ▩▩
        //// map에서 읽은 데이터를 이용해서 board 배열을 채우시오.  다음은 board 배열에 채워진
        //// 모습니다.
        //// ┌ ┐┌ ┐┌ ┐▩▩┌ ┐
        //// └ ┘└ ┘└ ┘▩▩└ ┘
        //// ┌ ┐▩▩┌ ┐▩▩┌ ┐
        //// └ ┘▩▩└ ┘▩▩└ ┘
        //// ┌ ┐┌ ┐┌ ┐┌ ┐┌ ┐
        //// └ ┘└ ┘└ ┘└ ┘└ ┘
        //
        //{
        //     // 코드를 작성하는 공간
        //
        //
        //
        //    System.out.println(“board 그리기 완료”);
        //}

        //보드 윤곽 넣기
        {
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 10; j++) {
                    if ((i % 2 == 0))
                        if (j % 2 == 0)
                            board[i][j] = '┌';
                        else
                            board[i][j] = '┐';
                    else if (j % 2 == 0)
                        board[i][j] = '└';
                    else
                        board[i][j] = '┘';
                }
                System.out.println();
            }
        }

        //이상한 네모 입력
        {
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 5; j++) {
                    if (map[i][j] == 1) {
                        int row = i * 2;
                        int col = j * 2;
                        board[row][col] = '▩';
                        board[row][col + 1] = '▩';
                        board[row + 1][col] = '▩';
                        board[row + 1][col + 1] = '▩';
                    }
                }
        }

        //출력
        {
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 10; j++) {

                    System.out.printf("%c", board[i][j]);
                }
                System.out.println();
            }
        }


        //// 5. board 배열을 화면에 출력하는 코드를 작성하시오.
        //
        //{
        //     // 코드를 작성하는 공간
        //
        //
        //
        //    System.out.println(“board 출력 완료”);
        //}
    }
}

 


👍좋았던 점👍

  • 연산자, 조건문과 반복문, 배열... 이전에 배운 모든 내용들이 다 들어가 있어서 복습 겸 실력을 다질 수 있어서 좋았음.

🔥어려웠던 점🔥

 

  • 위에 있는 좌표를 (x,y) -> (0, 1) 이런식으로 해석하며 풀어야 하는데....정수 23, 45 이런식으로 생각을 해버려서 Index 규칙찾는게 어려웠다.
  • 배열의 Index는 0부터 시작하는데...나도 모르게 1부터 카운트해서 규칙을 못 찾고 헤메고 있었다.

✅ 문제

// 1. res/bitmap.txt 파일을 생성하고 다음 데이터를 복사/붙여넣으시오.

11111111110000000000
11111111100000000000
11111111000000000000
11111110000000000000
11111100000000000000
11111000000000000000
11110000000000000000
11100000000000000000
11000000000000000000
10000000000000000000


2. bitmap이라는 이름으로 20X10크기의 정수를 담을 수 있는 이차원 배열을 생성하시오.

[           ]  bitmap = [                                      ];

3. 다음 그림과 같은 모양이 되도록 값의 위치를 변경하시오
00000000001111111111
00000000000111111111
00000000000011111111
00000000000001111111
00000000000000111111
00000000000000011111
00000000000000001111
00000000000000000111
00000000000000000011
00000000000000000001

{
     // 코드를 작성하는 공간



    System.out.println(“자리변경 완료”);
}


// 4. res/bitmap-out.txt 파일로 bitmap 배열의 값들을 저장 
{
     // 코드를 작성하는 공간

    

    System.out.println(“저장 완료”);

✅ 해결방법

  • bitmap [10][20] 이 있으면 [20]에 해당하는 값들을 좌우 대칭하게 바꿔줘야 한다.
  • 좌표로 생각하고 접근하면 편하다!

✅ 코드

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.Scanner;

        //문제 6 : 다음 각 절차를 따라 작성하시오.
        //
        //// 1. res/bitmap.txt 파일을 생성하고 다음 데이터를 복사/붙여넣으시오.
        //
        //11111111110000000000
        //11111111100000000000
        //11111111000000000000
        //11111110000000000000
        //11111100000000000000
        //11111000000000000000
        //11110000000000000000
        //11100000000000000000
        //11000000000000000000
        //10000000000000000000
public class Ex_0629_01 {
    public static void main(String[] args) throws IOException {

        //2. bitmap이라는 이름으로 20X10크기의 정수를 담을 수 있는 이차원 배열을 생성하시오.
        // [           ]  bitmap = [                                      ];
        int[][] bitmap = new int[10][20];

        //파일 읽어오기 & 읽어온 파일 btimap 배열에 하나씩 담기.
        {
            FileInputStream fis = new FileInputStream("afterschool/res/bitmap.txt");
            Scanner fscan = new Scanner(fis);

            for (int i = 0; i < bitmap.length; i++) {
                String str = fscan.nextLine();
                for (int j = 0; j < bitmap[i].length; j++) {

                    String[] tokens = str.split("");
                    bitmap[i][j] = Integer.parseInt(tokens[j]);

                    System.out.print(bitmap[i][j]);
                }
                System.out.println();
            }

        //3. 다음 그림과 같은 모양이 되도록 값의 위치를 변경하시오
        //00000000001111111111
        //00000000000111111111
        //00000000000011111111
        //00000000000001111111
        //00000000000000111111
        //00000000000000011111
        //00000000000000001111
        //00000000000000000111
        //00000000000000000011
        //00000000000000000001

            //값 바꾸기 정렬
            //bitmap.length "10", bitmap.length[i][] "20"
            for (int i = 0; i < bitmap.length; i++)
                for (int j = 0; j < bitmap[i].length/2; j++) {
                    int temp = bitmap[i][(bitmap[i].length-1) - j];
                    bitmap[i][(bitmap[i].length-1) - j] = bitmap[i][j];
                    bitmap[i][j] = temp;
                }
            //i 0        |  1        |        2 |        3 | ....
            //j 0 <-> 19 |  1 <-> 18 | 2 <-> 17 | 3 <-> 16 | ....
        }

        System.out.println("자리변경 완료");

        //i=10 j=20
        for (int i = 0; i < bitmap.length; i++) {
            for (int j = 0; j < bitmap[i].length; j++) {
                System.out.print(bitmap[i][j]);
            }
            System.out.println();
        }

        // 4. res/bitmap-out.txt 파일로 bitmap 배열의 값들을 저장
        {
            FileOutputStream fos = new FileOutputStream("afterschool/res/bitmap_out.txt");
            PrintWriter fout = new PrintWriter(fos, true, Charset.forName("UTF-8"));

            for (int i = 0; i < bitmap.length; i++) {
                for (int j = 0; j < bitmap[i].length; j++) {
                    fout.print(bitmap[i][j]);
                }
                fout.println();
            }
                fout.close();
                fos.close();
        }
    }

    }

 


🔥어려웠던 점🔥

  • 아래 좌우 대칭하게 값을 바꾸는 방법을 생각하는데 어려웠었다.
  • 데이터의 값의 갯수는 20개이고, 좌우 대칭하게 바꿔주면 10번만 반복하면 된다.
  • 두 번째 for문안에 Index를 "나누기 2"를 안해줘서 못하고 있었지만... 옆에 착한 짝꿍 누나가 팁을 줘서 해결! 
//값 바꾸기 정렬
//bitmap.length "10", bitmap.length[i][] "20"
for (int i = 0; i < bitmap.length; i++)
    for (int j = 0; j < bitmap[i].length/2; j++) {
        int temp = bitmap[i][(bitmap[i].length-1) - j];
        bitmap[i][(bitmap[i].length-1) - j] = bitmap[i][j];
        bitmap[i][j] = temp;
    }
//i 0        |  1        |        2 |        3 | ....
//j 0 <-> 19 |  1 <-> 18 | 2 <-> 17 | 3 <-> 16 | ....

https://beastit.tistory.com/77

 

[JAVA] ✏️ 로또 프로그램 만들기! (Bottom-Up)

✅ 문제 // 1. 로또 자동 생성 만들기! // 2. 로도 수동 생성 만들기! // 3. 내 로또 번호 보기 (Load) // 4. 종료! ✅ 해결방법 번호 자동으로 받기를 선택하면 중복값이 나오게 되는데, 중복되지 않는 수

beastit.tistory.com

👆👆👆이전에 작성한 버전을 구조화해서 메서드(Method)로 구현한 버전이다.👆👆👆


 

✅ 문제

// 1. 로또 자동 생성 만들기!
// 2. 로도 수동 생성 만들기!
// 3. 내 로또 번호 보기 (Load)
// 4. 종료!

✅ 해결방법

  • 번호 자동으로 받기를 선택하면 중복값이 나오게 되는데, 중복되지 않는 수를 받기!
  • 사용자로부터 수동으로 번호를 입력받게 되면 , " 1~45 숫자 범위 & 중복 값 "이 나오면 다시 입력받게 하기
  • 자동, 수동으로 로또번호를 받고 데이터로 따로 저장한 후 불러오기하면 보일 것!

✅ 코드

package 방과후연습용.Jin;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.Random;
import java.util.Scanner;

public class EX_0628_Program_Structured {
    public static void main(String[] args) throws IOException {
        //lottos[0][] -> 번호 자동생성, lottos[1][] -> 번호 수동생성
        //상수(constant) final을 이용해서 auto, manual을 구분하였음.
        final int auto = 0;
        final int manual = 1;

        int[][] lottos = new int[2][6];



        QUIT:
        while (true) {
            //메뉴 출력 & 번호 입력
           int menu = inputMeun();

            switch (menu) {
                case 1: {
                    //자동 로또 출력 메서드
                    autoOutputLotto(lottos,auto);
                    break;
                }
                case 2: {
                    //수동 로또 출력 메서드
                    manualOutputLotto(lottos,manual);
                    break;

                }
                case 3: {
                    //로또 불러오기
                    loadLotto();
                    break;
                }
                case 4: {
                    System.out.println("종료");
                    break QUIT;
                }
                default:
                    System.out.println("1~4값만 입력하세요.");

            }
        }//end while
    }

    private static void loadLotto() throws IOException{
        FileInputStream fis = new FileInputStream("JavaPrj/res/ALottos_save.txt");
        FileInputStream fis1 = new FileInputStream("JavaPrj/res/MLottos_save.txt");
        Scanner sc = new Scanner(fis);
        Scanner sc1 = new Scanner(fis1);

        System.out.println("┌───────────────────────────┐");
        System.out.println("      로또를 불러옵니다...      ");
        System.out.println("└───────────────────────────┘");
        System.out.println();

        //nextLine으로 한번에 받아옴. (정수형으로 연산작업하는 일이 없어서 String으로 받아옴)
        String autoLotto = sc.nextLine();
        String manualLotto = sc1.nextLine();

        sc1.close();
        sc.close();
        fis1.close();
        fis.close();

        System.out.printf("자동 로또번호 %s\n", autoLotto);
        System.out.printf("수동 로또번호 %s\n", manualLotto);
    }

    private static void manualOutputLotto(int[][] lottos, int manual) throws IOException{
        Scanner scan = new Scanner(System.in);

        System.out.println("┌───────────────────────────┐");
        System.out.println("     Lotto 번호 수동 생성     ");
        System.out.println("└───────────────────────────┘");

        Scanner scan1 = new Scanner(System.in);

        boolean onOff = true;

        AGAIN:
        do {
            //사용자의 입력값을 한줄로 받아옴.
            System.out.println("┌───────────────────────────┐");
            System.out.println("    1 ~ 45 숫자를 입력하세요  ");
            System.out.println("    예) 1 2 23 24 28 45     ");
            System.out.println("└───────────────────────────┘");
            System.out.print("입력 > ");

            //문자열로 한번에 받아옴.
            String input = scan1.nextLine();
            String[] arr = input.split(" ");

            //문자열로 받아온 숫자를 정수로 변환해줌.
            for (int i = 0; i < 6; i++)
                lottos[manual][i] = Integer.valueOf(arr[i]);

            //입력범위 설정
            for (int j = 0; j < 6; j++)
                if ((lottos[manual][j] < 1 || 45 < lottos[manual][j])) {
                    System.out.println("┌──────────────────────────────────┐");
                    System.out.println( " ★ 1~ 45 범위의 숫자를 입력하세요.★     ");
                    System.out.println("└──────────────────────────────────┘");
                    System.out.println("\n   ");
                    continue AGAIN;
                }

            //중복제거
            {
                for (int i = 0; i < 6; i++) {
                    for (int j = 0; j < i; j++) {
                        if (lottos[manual][i] == lottos[manual][j]) { // 중복 검사
                            System.out.println("\n  ♨ 중복된 요소가 있습니다! ♨\n");
                            continue AGAIN;
                        }
                    }
                }
                //i 0 |  1 |   2 |     3 |       4 |         5
                //j - |  0 | 0 1 | 0 1 2 | 0 1 2 3 | 0 1 2 3 4
            }

            //로또 저장
            System.out.println("┌───────────────────────────┐");
            System.out.println("          저장하실?           ");
            System.out.println("└───────────────────────────┘");
            System.out.println();
            System.out.println("\n1. 저장하고 메인메뉴로 가기");
            System.out.println("2. 취소하고 메인메뉴로 가기");
            System.out.print(">_ ");

            int meun2 = scan.nextInt();


            switch (meun2) {
                case 1: {
                    System.out.print("\n저장했습니다.");
                    FileOutputStream fos = new FileOutputStream("JavaPrj/res/MLottos_save.txt");
                    PrintWriter fout = new PrintWriter(fos, true, Charset.forName("UTF-8"));

                    for (int i = 0; i < 6; i++)
                        fout.printf("%d ", lottos[manual][i]);
                    fout.println();

                    fout.close();
                    fos.close();
                    System.out.println();
                    break;
                }
                case 2: {
                    System.out.println("♨ 저장하지 않고 메인 메뉴로 돌아갑니다. ♨");
                    break;
                }
            }
            onOff = false;
        } while (onOff);
    }

    private static void autoOutputLotto(int[][] lottos, int auto) throws IOException {
        Scanner scan = new Scanner(System.in);
        Random rand = new Random();
        System.out.println("┌───────────────────────────┐");
        System.out.println("     Lotto 번호 자동 생성     ");
        System.out.println("└───────────────────────────┘");
        System.out.println("┌───────────────────────────┐");
        System.out.println("   ↓  ★☆ 로또 번호 ★☆  ↓    ");
        System.out.println("└───────────────────────────┘");

        //랜덤한 값 추출 & 중복제거
        {
            for (int i = 0; i < 6; i++) {
                lottos[auto][i] = rand.nextInt(45) + 1;//Random(45)는 0~44까지의 범위를 만든다. 그래서 +1
                for (int j = 0; j < i; j++) {
                    if (lottos[auto][i] == lottos[auto][j])
                        i--;
                }
            }
        }

        //추출한 값 작은 숫자부터 정렬(선택정렬)
        {
            for (int i = 0; i < 6 - 1; i++) {
                int minIndex = i;
                for (int j = 0; j < (6 - 1) - i; j++) {
                    if (lottos[auto][minIndex] > lottos[auto][j + 1 + i])
                        minIndex = i + j + 1;
                }
                int temp = lottos[auto][i];
                lottos[auto][i] = lottos[auto][minIndex];
                lottos[auto][minIndex] = temp;
            }
        }
        //로또 출력
        {
            for (int j = 0; j < 6; j++)
                System.out.printf("(%d) ", lottos[auto][j]);
        }
        System.out.println();


        System.out.println("\n1. 저장하고 메인메뉴로 가기");
        System.out.println("2. 취소하고 메인메뉴로 가기");
        System.out.print(">_ ");

        int meun2 = scan.nextInt();

        switch (meun2) {
            case 1: {
                System.out.print("\n    ☆★저장했습니다.☆★ ");
                FileOutputStream fos = new FileOutputStream("JavaPrj/res/ALottos_save.txt");
                PrintWriter fout = new PrintWriter(fos, true, Charset.forName("UTF-8"));

                for (int i = 0; i < 6; i++)
                    fout.printf("%d ", lottos[auto][i]);

                fout.println();

                fout.close();
                fos.close();
                System.out.println();
                break;
            }
            case 2: {
                System.out.println("저장하지 않고 메인 메뉴로 돌아갑니다.");
                break;
            }
        }
    }

    private static int inputMeun() {
        Scanner scan = new Scanner(System.in);
        System.out.println("┌───────────────────────────┐");
        System.out.println("            ★\"★            ");
        System.out.println("          ★Lotto★          ");
        System.out.println("           ★^o^★           ");
        System.out.println("└───────────────────────────┘");
        System.out.println();

        System.out.println("1. 번호 자동 생성");
        System.out.println("2. 번호 수동 생성");
        System.out.println("3. 내 로또 번호 보기");
        System.out.println("4. 종료");
        System.out.print("선택 >");
        int menu = scan.nextInt();
        return menu;
    }
}

👍좋았던 점👍

  • 메서드로 큰 구성단위들을 묶어놓으니 main함수 부분에서 흐름을 이해하기 편했다.
  • 앞으로 추가될 내용이 있으면 메서드 부분만 수정해야 하니 유지보수가 편리할 거 같았다.

🔥어려웠던 점🔥

  • 사용자로부터 입력값을 "nextLine();"으로 받아오면 String 배열 split(메서드)로 하나씩 담아주는 작업 
  • String으로 받아온 값을 int형으로 변환해주는 작업.
//중복제거
{
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < i; j++) {
            if (lottos[manual][i] == lottos[manual][j]) { // 중복 검사
                System.out.println("\n     중복된 요소가 있습니다! ");
                continue AGAIN;
            }
        }
    }
    //i 0 |  1 |  2  |   3   |    4    |     5
    //j - |  0 | 0 1 | 0 1 2 | 0 1 2 3 | 0 1 2 3 4
}
  • 사용자로부터 입력 받은 값 중복 제거 해주는 작업이 제일 어려웠다.

✅ 문제

// 1. 로또 자동 생성 만들기!
// 2. 로도 수동 생성 만들기!
// 3. 내 로또 번호 보기 (Load)
// 4. 종료!

✅ 해결방법

  • 번호 자동으로 받기를 선택하면 중복값이 나오게 되는데, 중복되지 않는 수를 받기!
  • 사용자로부터 수동으로 번호를 입력 받게 되면 , " 1~45 숫자 범위 & 중복 값 "이 나오면 다시 입력받게 하기
  • 자동, 수동으로 로또번호를 받고 데이터로 따로 저장한 후 불러오기하면 보일 것!

✅ 코드

package 방과후연습용.Jin;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Random;
import java.util.Scanner;
import java.util.SplittableRandom;

public class EX_0628_Program {
    public static void main(String[] args) throws IOException {
        //lottos[0][] -> 번호 자동생성, lottos[1][] -> 번호 수동생성
        final int auto = 0;
        final int manual = 1;

        int[][] lottos = new int[2][6];

        Scanner scan = new Scanner(System.in);
        Random rand = new Random();

        QUIT:
        while (true) {
            System.out.println("┌───────────────────────────┐");
            System.out.println("      Lotto 관리 프로그램     ");
            System.out.println("└───────────────────────────┘");
            System.out.println();

            System.out.println("1. 번호 자동 생성");
            System.out.println("2. 번호 수동 생성");
            System.out.println("3. 내 로또 번호 보기");
            System.out.println("4. 종료");
            System.out.print("선택 >");
            int menu = scan.nextInt();


            switch (menu) {
                case 1: {
                    System.out.println("┌───────────────────────────┐");
                    System.out.println("     Lotto 번호 자동 생성     ");
                    System.out.println("└───────────────────────────┘");
                    System.out.println("┌───────────────────────────┐");
                    System.out.println("          로또 번호           ");
                    System.out.println("└───────────────────────────┘");
                    System.out.println();

                    //랜덤한 값 추출 & 중복제거
                    {
                        for (int i = 0; i < 6; i++) {
                            lottos[auto][i] = rand.nextInt(45) + 1;//Random(45)는 0~44까지의 범위를 만든다. 그래서 +1
                            for (int j = 0; j < i; j++) {
                                if (lottos[auto][i] == lottos[auto][j])
                                    i--;
                            }
                        }
                    }

                    //추출한 값 작은 숫자부터 정렬(선택정렬)
                    {
                        for (int i = 0; i < 6 - 1; i++) {
                            int minIndex = i;
                            for (int j = 0; j < (6 - 1) - i; j++) {
                                if (lottos[auto][minIndex] > lottos[auto][j + 1 + i])
                                    minIndex = i + j + 1;
                            }
                            int temp = lottos[auto][i];
                            lottos[auto][i] = lottos[auto][minIndex];
                            lottos[auto][minIndex] = temp;
                        }
                    }
                    //로또 출력
                    {
                        for (int j = 0; j < 6; j++)
                            System.out.printf("(%d) ", lottos[auto][j]);
                    }
                    System.out.println();


                    System.out.println("\n1. 저장하고 메인메뉴로 가기");
                    System.out.println("2. 취소하고 메인메뉴로 가기");
                    System.out.print(">_ ");

                    int meun2 = scan.nextInt();

                    switch (meun2) {
                        case 1: {
                            System.out.print("\n저장했습니다.");
                            FileOutputStream fos = new FileOutputStream("JavaPrj/res/ALottos_save.txt");
                            PrintWriter fout = new PrintWriter(fos, true, Charset.forName("UTF-8"));

                            for (int i = 0; i < 6; i++)
                                fout.printf("%d ", lottos[auto][i]);

                            fout.println();

                            fout.close();
                            fos.close();
                            System.out.println();
                            break;
                        }
                        case 2: {
                            System.out.println("저장하지 않고 메인 메뉴로 돌아갑니다.");
                            break;
                        }
                    }

                    break;
                }
                case 2: {
                    System.out.println("┌───────────────────────────┐");
                    System.out.println("     Lotto 번호 수동 생성     ");
                    System.out.println("└───────────────────────────┘");

                    Scanner scan1 = new Scanner(System.in);

                    boolean onOff = true;

                    AGAIN:
                    do {
                        //사용자의 입력값을 한줄로 받아옴.
                        System.out.println("    1 ~ 45 숫자를 입력하세요  ");
                        System.out.println("    예) 1 2 23 24 28 45     ");
                        System.out.print("입력 > ");

                        //문자열로 한번에 받아옴.
                        String input = scan1.nextLine();
                        String[] arr = input.split(" ");

                        //문자열로 받아온 숫자를 정수로 변환해줌.
                        for (int i = 0; i < 6; i++)
                            lottos[manual][i] = Integer.valueOf(arr[i]);

                        //입력범위 설정
                        for (int j = 0; j < 6; j++)
                            if ((lottos[manual][j] < 1 || 45 < lottos[manual][j])) {
                                System.out.println("\n   1~ 45 범위의 숫자를 입력하세요.");
                                continue AGAIN;
                            }


                        //중복제거
                        {
                            for (int i = 0; i < 6; i++) {
                                for (int j = 0; j < i; j++) {
                                    if (lottos[manual][i] == lottos[manual][j]) { // 중복 검사
                                        System.out.println("\n     중복된 요소가 있습니다! ");
                                        continue AGAIN;
                                    }
                                }
                            }
                            //i 0 |  1 |  2  |   3   |    4    |     5
                            //j - |  0 | 0 1 | 0 1 2 | 0 1 2 3 | 0 1 2 3 4
                        }
                        System.out.println("\n1. 저장하고 메인메뉴로 가기");
                        System.out.println("2. 취소하고 메인메뉴로 가기");
                        System.out.print(">_ ");

                        int meun2 = scan.nextInt();

                        switch (meun2) {
                            case 1: {
                                System.out.print("\n저장했습니다.");
                                FileOutputStream fos = new FileOutputStream("JavaPrj/res/MLottos_save.txt");
                                PrintWriter fout = new PrintWriter(fos, true, Charset.forName("UTF-8"));

                                for (int i = 0; i < 6; i++)
                                    fout.printf("%d ", lottos[manual][i]);
                                fout.println();

                                fout.close();
                                fos.close();
                                System.out.println();
                                break;
                            }
                            case 2: {
                                System.out.println("저장하지 않고 메인 메뉴로 돌아갑니다.");
                                break;
                            }
                        }
                        onOff = false;
                    } while (onOff);

                    break;

                }
                case 3: {
                    FileInputStream fis = new FileInputStream("JavaPrj/res/ALottos_save.txt");
                    FileInputStream fis1 = new FileInputStream("JavaPrj/res/MLottos_save.txt");
                    Scanner sc = new Scanner(fis);
                    Scanner sc1 = new Scanner(fis1);

                    System.out.println("┌───────────────────────────┐");
                    System.out.println("      로또를 불러옵니다...      ");
                    System.out.println("└───────────────────────────┘");
                    System.out.println();

                    String autoLotto = sc.nextLine();
                    String manualLotto = sc1.nextLine();

                    sc1.close();
                    sc.close();
                    fis1.close();
                    fis.close();

                    System.out.printf("자동 로또번호 %s\n", autoLotto);
                    System.out.printf("수동 로또번호 %s\n", manualLotto);

                    break;
                }
                case 4: {
                    System.out.println("종료");
                    break QUIT;
                }
                default:
                    System.out.println("1~4값만 입력하세요.");

            }
        }//end while
    }
}

🔥어려웠던 점🔥

  • 사용자로부터 입력값을 "nextLine();"으로 받아오면 String 배열split(메서드)로 하나씩 담아주는 작업 
  • String으로 받아온 값을 int형으로 변환해주는 작업.
//중복제거
{
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < i; j++) {
            if (lottos[manual][i] == lottos[manual][j]) { // 중복 검사
                System.out.println("\n     중복된 요소가 있습니다! ");
                continue AGAIN;
            }
        }
    }
    //i 0 |  1 |  2  |   3   |    4    |     5
    //j - |  0 | 0 1 | 0 1 2 | 0 1 2 3 | 0 1 2 3 4
}
  • 사용자로부터 입력 받은 값중복 제거 해주는 작업이 제일 어려웠다.

https://beastit.tistory.com/71

 

[JAVA] ✏️ 오목 게임 프로그램을 만들어보자!(2차원 배열)

https://beastit.tistory.com/60 [JAVA] ✏️ 입력받은 좌표로 바둑알을 "오목판"을 출력해보자 [심화] 🎛 ✅문제 💡[아이디어] 오목판에 좌표값을 입력 받아 해당 좌표에 구현해볼 생각을 했다. X, Y값을

beastit.tistory.com

 

앞에서 2차원 배열로 값을 저장시켜 오목이 누적되게 만들었다.

 

이번에는 오목실행 중 저장(데이터값으로)하고 불러와서 다시 실행할 수 있게 구현해 보았다.

 


✅코드

 

import java.io.*;
import java.nio.charset.Charset;
import java.util.Scanner;

public class Program3_SaveLoad {
    public static void main(String[] args) throws IOException {
        final int empty=0;//데이터로 저장하기 위한 값.
        final int blackStone=1;//검돌 저장데이터 값.
        final int whiteStone=2;//흰돌 저장데이터 값.

        int[][] save=new int[12][12];//데이터 저장 변수.
        boolean[][] saveChk=new boolean[12][12];//중복값 저장 변수
        char[][] saveBoard=new char[12][12];//보드값 저장

        boolean loadswitch = false;

        //countBefore
        int countBefore=1;

        QUIT:
        while (true) {

            char board[][] = new char[12][12];// 12*12 바둑판 배열
            boolean chk[][] = new boolean[12][12];//중복값 판별용 배열
            // ----------------------------------------------------
            // ----------------------------------------------------
            int ox = -1; // 돌
            int oy = -1; // 돌

            //이전좌표
            int xBefore = -1;
            int yBefore = -1;

            // ----------------------------------------------------초기 바둑판 양식 배열에 저장
            for (int x = 0; x < 12; x++) {
                for (int y = 0; y < 12; y++) {
                    if (x == 0 && y == 0) {// 왼쪽 위 모서리막기
                        board[x][y] = '┌';
                        saveBoard[x][y]='┌';
                    }
                    else if (x == 11 && y == 11){// 오른쪽 아래 모서리막기
                        board[x][y] = '┘';
                        saveBoard[x][y]='┘';
                    }
                    else if (x == 11 && y == 0) {// 왼쪽 아래 모서리막기
                        board[x][y] = '└';
                        saveBoard[x][y] = '└';
                    }
                    else if (x == 0 && y == 11) {// 오른쪽 위 모서리막기
                        board[x][y] = '┐';
                        saveBoard[x][y] = '┐';
                    }
                    else if (x == 0) {// 위에 막기
                        board[x][y] = '┬';
                        saveBoard[x][y] = '┬';
                    }
                    else if (x == 11) {// 아래 막기
                        board[x][y] = '┴';
                        saveBoard[x][y] = '┴';
                    }
                    else if (y == 0) {// 왼쪽 막기
                        board[x][y] = '├';
                        saveBoard[x][y] = '├';
                    }
                    else if (y == 11) {// 오른쪽 막기
                        board[x][y] = '┤';
                        saveBoard[x][y] = '┤';
                    }
                    else {
                        board[x][y] = '┼';
                        saveBoard[x][y] = '┼';
                    }
                }
            }

            Scanner scan = new Scanner(System.in);

            System.out.println("┌───────────────────────────┐");
            System.out.println("│          Omok Game        │");
            System.out.println("└───────────────────────────┘");
            System.out.println();

            System.out.println("1. 게임시작");
            System.out.println("2. 도움말");
            System.out.println("3. 저장하기");
            System.out.println("4. 불러오기");
            System.out.println("5. 종료");
            System.out.print(">");
            int option = scan.nextInt();


            //저장값 불러오기
            if(loadswitch){
                        for(int i=0;i<12;i++)
                            for(int j=0;j<12;j++) {
                                if(save[i][j]==1) {
                                    chk[i][j] = saveChk[i][j];//중복값 T & F
                                    saveBoard[i][j] = '○';;//바둑판정보
                                    board[i][j]=saveBoard[i][j];
                                }

                                if(save[i][j]==2) {
                                    chk[i][j] = saveChk[i][j];//중복값 T & F
                                    saveBoard[i][j] = '●';;//바둑판정보
                                    board[i][j]=saveBoard[i][j];
                                }
                            }
                    }


            switch (option) {
                //1. 게임시작
                case 1: {
                     int count = 1;// 홀수일때 흰돌, 짝수일때 검돌

                    if(loadswitch)
                    count=countBefore;

                    GAMEOVER:
                    while (true) {

                        //중복 제거 & 바둑알 넣기 & 첫 사이클은 그냥 지나침.
                        //첫 사이클부터 통과하면 배열 변수 초기값 -1이여서 오류발생!
                        if (ox != -1 && oy != -1 && !chk[ox][oy]) {
                            xBefore = ox;
                            yBefore = oy;

                            if (count % 2 == 1) {
                                board[ox][oy] = '○';
                                save[ox][oy]=blackStone;
                            }
                            else if (count % 2 == 0) {
                                board[ox][oy] = '●';
                                save[ox][oy]=whiteStone;
                            }

                            chk[ox][oy] = true;
                            saveChk[ox][oy]=true;
                            count++;
                            countBefore=count;
                            loadswitch=false;

                            System.out.printf("☆이전 좌표 : [%2d][%2d]☆\n", xBefore, yBefore);
                        } else if (countBefore>1 && count>1)
                            System.out.println("\n☆★☆★고민해보세요!☆★☆★");

                        // 배열 바둑판 출력 양식.
                        {
                            for (int i = 0; i < 12; i++) {
                                for (int j = 0; j < 12; j++) {
                                    System.out.print(board[i][j]);
                                }
                                System.out.println();
                            }
                        }

                        //좌표 입력
                        do {
                            System.out.println("\n그만두기:-1");
                            if (count % 2 == 1)
                                System.out.println("○ 흑돌 차례입니다");
                            else
                                System.out.println("● 백돌 차례입니다");
                            System.out.print(" x sp y> ");


                            ox = scan.nextInt();
                            if (ox == -1) {
                                System.out.println("GAMEOVER~~");
                                break GAMEOVER;
                            }
                            oy = scan.nextInt();

                            //1~11 범위를 벗어나면 배열 Index오류 발생!! ☆★중요☆★ 예) 15입력시 오류발생해서 멈춤...
                            if (!(1 <= ox && ox <= 11) || !(1 <= oy && oy <= 11)) {
                                System.out.println("\n              ♨경고♨                ");
                                System.out.println("오목 좌표의 범위(-1 or 1~11)를 벗어났습니다.");
                            }

                        } while (!(1 <= ox && ox <= 11) || !(1 <= oy && oy <= 11));
                        System.out.println("==================================");

                    }
                }
                break;

                //2. 도움말
                case 2: {
                    System.out.println("좌표를 입력하면 게임을 할 수 있다");
                    break QUIT;
                }
                //3. 저장하기.
                case 3: {
                    System.out.println("┌───────────────────────────┐");
                    System.out.println("       게임을 저장합니다.      ");
                    System.out.println("└───────────────────────────┘");
                    System.out.println();

                    FileOutputStream fos = new FileOutputStream("JavaPrj/res/Data/Omok_save.txt");
                    PrintWriter fout = new PrintWriter(fos, true, Charset.forName("UTF-8"));

                    //save[][]에 데이저 저장
                    {
                        for (int i=0;i<12;i++) {
                            for (int j = 0; j < 12; j++)
                                fout.printf("%d ", save[i][j]);
                            fout.println();
                        }
                        fout.printf("%d ", countBefore);
                    }
                    System.out.println("┌───────────────────────────┐");
                    System.out.println("      게임을 저장 했습니다.    ");
                    System.out.println("└───────────────────────────┘");
                    System.out.println();

                    fout.close();
                    fos.close();
                    break;
                }
                //4. 불러오기
                case 4: {
                    FileInputStream fis = new FileInputStream("JavaPrj/res/Data/Omok_save.txt");
                    Scanner sc = new Scanner(fis);

                    //파일 읽어와서 save[][]에 저장
                    {
                        for (int i=0;i<12;i++) {
                            for (int j = 0; j < 12; j++)
                                save[i][j]=sc.nextInt();
                            System.out.println();
                        }
                        countBefore=sc.nextInt();
                    }

                    //출력확인용 테스트코드
//                    {
//                        for (int i=0;i<12;i++) {
//                            for (int j = 0; j < 12; j++)
//                                System.out.printf("%d ", save[i][j]);
//                            System.out.println();
//                        }
//                        System.out.println(countBefore);
//                    }

                    sc.close();
                    fis.close();

                    loadswitch=true;
                    break;
                }
                //5. 종료
                case 5: {
                    System.out.println("종료");
                    break QUIT;
                }
                default:
                {
                    System.out.println("1~3까지 숫자만 입력하세요");
                    break;
                }
            }
        }
    }
}

 

✅ 실행

 

그만두게 되면 아래처럼 데이터 형식으로 저장되게 된다.

 

 

 

3번을 눌러서 게임을 저장한다.

 

검은색돌(1), 흰돌(2), 빈공간(0)

이런 식으로 데이터를 저장하게 된다.

아래 숫자 10은 다음 게임 때게임의 순서(검은색 or 흰색)를 위해 따로 받아온 값이다.

 

저장한 상태에서 다시 게임 시작을 누르면 게임은 초기화가 돼서 처음부터 다시 오목을 시작할 수 있다.

 

 

이제 이전에 했던 플레이 기록을 불러와보겠다.

 

 

 

불러오게 되면 이전 바둑돌을 그대로 가져오고, 플레이 순서까지 동일하게 가져오는 모습을 볼 수 있다.

 

🚨어려웠던 점🚨

  • 머리로는 알겠지만, 막상 코드에 적용하려니 흐름이 바뀌어서 어려움을 겪었다...
  • 흐름에 대해서 손으로 써보고 조금 더 구조화시켜서 코드작성하는 습관을 길러야겠음..

https://beastit.tistory.com/60

 

[JAVA] ✏️ 입력받은 좌표로 바둑알을 "오목판"을 출력해보자 [심화] 🎛

✅문제 💡[아이디어] 오목판에 좌표값을 입력 받아 해당 좌표에 구현해볼 생각을 했다. X, Y값을 입력 받아서 "오목판"에 바둑알을 출력해라! ✅문제 해설 바둑알은 흰색, 검은색 2개가 있다. X, Y

beastit.tistory.com

 

위 링크는 배열을 배우기 전에 콘솔을 사용하여 오목판을 만들고 좌표값을 입력하면 바둑알이 표시되게 만들었다.

 

다른 좌표값을 입력하면 변숫값이 다른 값으로 바뀌어서 실제 게임처럼 구현을 못한다.

 

이번에 배열을 배워서 값을 누적시키고, 실제 게임처럼 만들기 위해 다시 만들어봤다.

 


✅ 코드

import java.util.Scanner;

public class Program2 {
    public static void main(String[] args) {
        char board[][] = new char[12][12];// 12*12 바둑판 배열
        boolean chk[][] = new boolean[12][12];//중복값 판별용 배열

        // ----------------------------------------------------초기 바둑판 양식 배열에 저장
        for (int x = 0; x < 12; x++) {
            for (int y = 0; y < 12; y++) {
                if (x == 0 && y == 0)// 왼쪽 위 모서리막기
                    board[x][y] = '┌';
                else if (x == 11 && y == 11)// 오른쪽 아래 모서리막기
                    board[x][y] = '┘';
                else if (x == 11 && y == 0)// 왼쪽 아래 모서리막기
                    board[x][y] = '└';
                else if (x == 0 && y == 11)// 오른쪽 위 모서리막기
                    board[x][y] = '┐';
                else if (x == 0)// 위에 막기
                    board[x][y] = '┬';
                else if (x == 11)// 아래 막기
                    board[x][y] = '┴';
                else if (y == 0)// 왼쪽 막기
                    board[x][y] = '├';
                else if (y == 11)// 오른쪽 막기
                    board[x][y] = '┤';
                else
                    board[x][y] = '┼';

                chk[x][y] = false;
            }
        }
        // ----------------------------------------------------
        int ox = -1; // 돌
        int oy = -1; // 돌

        //이전좌표
        int xBefore = -1;
        int yBefore = -1;

        QUIT:
        while (true) {
            Scanner scan = new Scanner(System.in);

            System.out.println("┌───────────────────────────┐");
            System.out.println("│          Omok Game        │");
            System.out.println("└───────────────────────────┘");
            System.out.println();

            System.out.println("1. 게임시작");
            System.out.println("2. 도움말");
            System.out.println("3. 종료");
            System.out.print(">");
            int option = scan.nextInt();

            switch (option) {
                //1. 게임시작
                case 1: {

                    int count = 1;// 홀수일때 흰돌, 짝수일때 검돌

                    GAMEOVER:
                    while (true) {

                        //중복 제거 & 첫 사이클은 그냥 지나침.
                        //첫 사이클부터 통과하면 배열 변수 초기값 -1이여서 오류발생!
                        if (ox != -1 && oy != -1 && !chk[ox][oy]) {
                            xBefore = ox;
                            yBefore = oy;

                            if (count % 2 == 1)
                                board[ox][oy] = '●';
                            else if (count % 2 == 0)
                                board[ox][oy] = '○';

                            chk[ox][oy] = true;
                            count++;

                            System.out.printf("☆이전 좌표 : [%2d][%2d]☆\n", xBefore, yBefore);
                        } else if (count > 1)
                            System.out.println("\n☆★☆★중복 좌표입니다.☆★☆★");

                        // 배열 바둑판 출력 양식.
                        {
                            for (int i = 0; i < 12; i++) {
                                for (int j = 0; j < 12; j++) {
                                    System.out.print(board[i][j]);
                                }
                                System.out.println();
                            }
                        }

                        //좌표 입력
                        do {
                            System.out.println("\n그만두기:-1");
                            if (count % 2 == 1)
                                System.out.println("● 백돌 차례입니다");
                            else
                                System.out.println("○ 흑돌 차례입니다");
                            System.out.print(" x sp y> ");


                            ox = scan.nextInt();
                            if (ox == -1) {
                                System.out.println("GAMEOVER~~");
                                break GAMEOVER;
                            }
                            oy = scan.nextInt();

                            //1~11 범위를 벗어나면 배열 Index오류 발생!! ☆★중요☆★ 예) 15입력시 오류발생해서 멈춤...
                            if (!(1 <= ox && ox <= 11) || !(1 <= oy && oy <= 11)) {
                                System.out.println("\n              ♨경고♨                ");
                                System.out.println("오목 좌표의 범위(-1 or 1~11)를 벗어났습니다.");
                            }

                        } while (!(1 <= ox && ox <= 11) || !(1 <= oy && oy <= 11));
                        System.out.println("==================================");

                    }
                }
                break;

                //2. 도움말.
                case 2: {
                    System.out.println("좌표를 입력하면 게임을 할 수 있다");
                    break;
                }
                //3. 종료
                case 3: {
                    System.out.println("종료");
                    break QUIT;
                }
            }
        }
    }
}

 

✅ 실행

 

 

🚨어려웠던 점🚨

  • 좌표값에 초기값으로 선언한 배열의 범위가 아닌 ' -1 '을 입력하니 Index out of bounds 오류가 발생함...
    • 위 문제를 해결하기 위해 초기에 작성한 코드를 다 지우고 새로운 흐름으로 만들었음.

 

  • Index out of bounds 오류를 해결하니... 중복값을 입력하면 바둑돌의 색이 바뀜! (미쳐버림..)
    • 위 문제를 해결하기 위해 다시 흐름 정리를 하였고, 이로 인해 많은 깨달음을 얻음!

+ Recent posts