🟩 문제


🟩 해결방법

  • split 메서드를 이용해서 하나씩 문자열 배열에 담아준 후 정수형 배열에 넣어서 계산!


🟩 코드

public static int solution(int n) {
        int answer = 0;

        String loadN = new String(String.valueOf(n));
        String[] separationN = loadN.split("");

        for (int i = 0; i < separationN.length; i++) {
            int[] numN = new int[separationN.length];
            numN[i] = Integer.parseInt(separationN[i]);

            answer = answer + numN[i];
        }

        return answer;
    }

🟩 문제


🟩 해결방법

  • 숫자를 더하면 숫자의 합이 나오니 문자열로 변환 후 합친다.
  • 문자열로 합친 숫자를 정수로 비교해서 조건 연산을 한다.


🟩 코드

 

public static int solution(int a, int b) {
        int answer = 0;

        //정수인 숫자를 문자로 변환
        String aa = String.valueOf(a);
        String bb = String.valueOf(b);

        //문자열인 두 숫자를 합쳐서 정수로 변환
        int aabb = Integer.valueOf(aa + bb);
        int aabb2 = 2 * a * b;

        //조건 판별식
        if (aabb > aabb2 || aabb == aabb2)
            answer = aabb;

        if (aabb < aabb2)
            answer = aabb2;

        return answer;
    }

✅ 문제

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 | ....

✅문제

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();            // 1)
String s = scan.nextLine();        // 2)

이렇게 사용하면 int만 받아오고 nextLine은 그냥 건너뛰게 되는 오류가 발생하게 될 것이다.

 

 nextInt()에서 Enter를 칠 때 발생하는 '개행문자'를 처리하지 않고 버퍼에 남기기 때문이다.

 

Scanner에 있는 개행문자 \r\n을 비워주어야 한다.

 

운영체제별 개행문자를 지정하는 문자열이 다른데 아래를 참고하면 된다.


✅ 운영체제별 개행문자(줄 바꿈)

LF(Line-Feed)

  • Mac, Linux (Unix 계열) 줄 바꿈 문자열 = \n
  • ASCII 코드 = 10
  • 커서 위치는 그대로 두고 종이의 한라인 위로 올리는 동작
  • 현재 위치에서 바로 아래로 이동
  • 종이를 한 칸 올리기

CR(Carriage-Return)

  • Mac 초기 모델 줄 바꿈 문자열 = \r
  • ASCII 코드 = 13
  • 커서 위치를 맨 앞으로 옮기는 동작
  • 커서 위치를 앞으로 이동

CRLF (Carriage-Return+Line-Feed)

  • Windows, DOS 줄 바꿈 문자열 = \r\n
  • CR(\r) + LR(\n) 두 동작을 합쳐서 (\r\n)
  • 커서를 다음라인 맨 앞으로 옮겨주는 동작

✅ 해결방법

 

1. 첫 번째 방법

  scan.nextLine();

 

2. 두 번째 방법

scan.skip("[\\r\\n]+");

 

두 가지 방법 중 하나를 사용하면 된다.

 

예시

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();            // 1)

//방법 1
scan.nextLine();

String s = scan.nextLine();        // 2)

------------------------------------------
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();            // 1)

//방법2
scan.skip("[\\r\\n]+");

String s = scan.nextLine();        // 2)

'IT > 🚨Error🚨' 카테고리의 다른 글

[Issue] 컴퓨터 메모리 누수 해결 방법  (2) 2024.06.03

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
}
  • 사용자로부터 입력 받은 값 중복 제거 해주는 작업이 제일 어려웠다.

+ Recent posts