✅ 문제

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

🟩 메서드란?

 

특정 작업을 수행하는 일련의 문장들을 하나로 묶은 것이다.


 

✅ 메서드를 사용하는 이유

  • 높은 재사용성 : 한번 만들어 놓은 메서드는 몇 번이고 호출할 수 있다.
  • 중복된 코드의 제거 : 반복되는 문장을 묶어서 메서드로 작성하면, 메서드를 호출하는 문장으로 대체할 수 있다.
  • 프로그램의 구조화 : 메서드를 사용해 main에서 전체 흐름이 한눈에 들어오게 구조화 가능하다.

 메서드의 선언과 구현

public static 반환값형식 함수명(인자형식)//메서드 선언부

public static int num(int a, int b){ //예시
	return 반환값;
}

num(3,4); //메서드 구현방법

 

반환하는것은 그 함수를 통해 무엇이 남는지? 남겨지는것을 한다.

 


public class Program2 {
    //로또번호 저장하기
    public static int[][] creatLottos(){
        int[][] lottos={{1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18}};

        return lottos;
    }
    //로또 출력
    public static void printLottos(int[][] lottos){
        for(int i=0;i<3;i++) {
            for (int j = 0; j < 6; j++)
                System.out.printf("%4d, ",lottos[i][j]);

            System.out.println();
        }
    }
    //로또 저장소 바꿔주기
    public static void swapLottos(int[][] lottos,int i,int j){
        int[] temp = lottos[i];
        lottos[i]=lottos[j];
        lottos[j]=temp;
    }

    public static void main(String[] args) {

        int[][] lottos = creatLottos();//로또번호 생성 후 lottos에 저장해주기
        
        //로또 출력
        printLottos(lottos);

        System.out.println("\n-----------첫번째와 세번째 바꾸기-----------\n");
        
        //로또 저장소 바꿔주기
        swapLottos(lottos,0,2);//값바꾸기
        
        //로또 출력
        printLottos(lottos);


    }
}

 


public class BasicProgram2 {
    static int sum(int n) {
        int total = (n * (n + 1)) / 2;
        return total;
    }

    static int power(int x) {
        return ((x + 3) * (x + 3) + x / 3 * (x - 2) + 5);
    }

    public static void main(String[] args) {
        //int result = 1+2+3+4+5+6+7+8+9+10~n;
        int result = sum(11);
        System.out.printf("result : %d\n", result);

        //(x+3)*(x+3)+ x/3*(x-2)+5
        int result2 = power(7) + 3 + power(7) - power(3);
        System.out.printf("result : %d\n", result2);

        int a1 = f1();
        int a2 = f2(20, 30);
        f3(33);
        f4(9);

//        int[] lotto = new int[3];
//        print(3,5.3f,lotto);


        char[][] names = new char[3][10];

        double cnt = print(true, 4.0, names);
    }

    static double print(boolean a, double b, char[][] c) {
        return 2.2;
    }

    //print(2,3.0f,'a') 함수로 만들어보자!
//    static void print(int i, float f,int[] a){
//        System.out.printf("출력 값 : %d %.2f %c\n",i,f,a[0]);
//    }
    private static void f4(int i) {
        System.out.printf("출력 값 : %d\n", i);
    }

    private static void f3(int i) {

    }

    private static int f2(int i, int i1) {
        return 0;
    }

    private static int f1() {
        return 0;
    }
}

 

'IT > JAVA' 카테고리의 다른 글

[Java] 컬렉션(Collection) ?  (1) 2023.07.09
[Java] 함수 오버로드(overload)  (1) 2023.07.04
[JAVA] 변수와 상수변수  (0) 2023.06.26
[Java] 배열(Array)  (0) 2023.06.21
[Java]비트 연산자로 데이터값 추출하기  (0) 2023.06.12

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 흰색)를 위해 따로 받아온 값이다.

 

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

 

 

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

 

 

 

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

 

🚨어려웠던 점🚨

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

상수형 변수가 필요한 경우

 

방향을 표현하고 싶은 변수가 있다고 가정해 보자.

 

4번 방향으로 가고 싶으면 다음과 같이 표시할 것이다.

int direction; direction = 4; direction = SE;


만약 위 사진이 없다면 4번 방향이 어딘지 모를 것이다.

int N = 1;		N(1);
int NE = 2;		NE(2);
int E = 3;		E(3);
int SE = 4;		SE(4);
int S = 5;		S(5);
int SW = 6;		SW(6);
int W = 7;		W(7);
int NW = 8;		NW(8);

 

위에 있는 값들은 고정적으로 사용할 값들이어서 바뀌면 안 된다.

 

변수가 바뀌지 않게 앞에 "final"을 붙여주면 된다. 이를 상수형 변수이다.

final int N = 1;		N(1);
final int NE = 2;		NE(2);
final int E = 3;		E(3);
final int SE = 4;		SE(4);
final int S = 5;		S(5);
final int SW = 6;		SW(6);
final int W = 7;		W(7);
final int NW = 8;		NW(8);

변수의 생명주기

프로그램을 실행시키면 text에 올라간다. 

 

Data영역heap영역 stack영역으로 나눠진다. (전역 데이터를 관리하는 공간) 

 

stack영역에 준비물 args, total, avg, kors (보라색은 참조변수, 초록색은 일반변수) 블록 들어가기 전에 예약석에 넣은 느낌이다. 그리고 자물쇠로 봉인.

 

참조변수 같은 경우는 주소값을 미리 부여받고 봉인! 바꿀수 없으니까 다른 메모리 영역(heap)에 저장하는것이다.

 

딱 stack이랑 heap이 나눠지는 게 아니고 stack을 할당하고 나머지 공간이 heap이 되는 것이다.

 

감시컬랙터(가비지 컬렉터)는 cpu가 한가할 때 쓰레기를 수거해 간다. 가비지는 heap에만 있다. 또 메모리가 부족한 경우가 오면 가비지 컬렉터가 또 돌아가긴 한다.

 


오류

  • 구문오류(컴파일러가 잡아준다.)
x=3;
3=x;

 

  • 논문오류(치명적)
total/5; (총 3명인데 5로 나눔)
//결과가 5.77..이렇게 만들어야하는데 정수로 나눠서 정수로만 값이 나옴

 

디버거를 사용해서 오류를 잡을 수  있다.

 

 


자바의 다차원 배열과 톱니형 배열

 

//lotto 번호를 저장하기 위한 1차원 배열
int[] lotto = new int[6];

하나의 번호만 저장할 수 있다.

 

//lotto 번호를 저장하기 위한 다차원 배열
int[][] lotto = new int[3][6];

3가지의 로또번호를 저장할 수 있다.

 

자바에서는 아래 그림처럼 다차원배열이 구성되어 있다.

배열을 바꾸고 싶으면 새로운 배열에 옮겨주면 된다.

 

public class Program {
    public static void main(String[] args) {
        //int[][] lottos=new int[3][6];
        //int[][] lottos=new int[3][6]{{1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18}};
        int[][] lottos={{1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18}};

        for(int i=0;i<3;i++) {
            for (int j = 0; j < 6; j++)
                System.out.printf("%4d, ",lottos[i][j]);

            System.out.println();
        }
        System.out.println("------ 0<->2 위치 변경 --------");

        int[] temp = lottos[0];
        lottos[0]=lottos[2];
        lottos[2]=temp;
        /*
        [1] <-> [2]

        lottos         ->2차 배열의 이름
        lottos[0]      ->1차 배열의 이름
        lottos[0][0]   ->정수 변수의 이름

        int x = lottos[0][0];     값 변수는 값을 대입하는 연산이 이루어진다.
        int[] xes = lottos[0][0]; (x) 계층이 달라요.
        int[] xes = lottos[0];    참조 변수는 새로운 이름을 만드는 것이다.
        int[] xes = lottos; (x)   계층이 달라요.
        int[][] xes = lottos;     (o) 쌉가능!

        */
        //이렇게 대입하면 처음에 선언한 배열 크기에 맞게 늘어간다.
        //다른 배열을 만들때는 new를 사용해서 해야한다.
        lottos[1]=new int []{9,9,9,9,9,9,9,9,9,9};

        for(int i=0;i<3;i++) {
            for (int j = 0; j < 6; j++)
                System.out.printf("%4d, ",lottos[i][j]);

            System.out.println();
        }

    }
}

'IT > JAVA' 카테고리의 다른 글

[Java] 함수 오버로드(overload)  (1) 2023.07.04
[Java]구조적인 프로그래밍(메서드)  (2) 2023.06.28
[Java] 배열(Array)  (0) 2023.06.21
[Java]비트 연산자로 데이터값 추출하기  (0) 2023.06.12
[Java] 문자열 (String)  (2) 2023.06.10

what?

 

혼자서 열심히 코딩하고 git에 수정한 코드들을 commit하기 위해 git add 를 하자마자...

 

warning: LF will be replaced by CRLF in ~~~ 
The file will have its original line endings in your working directory

이런 문구가 떴다! 무시하고 지나가려고했으나...warning...이 무서워서 찾아보았다.

 

🚨 아마 Mac에서 Windows로 프로젝트 파일을 가져와서 이런 문제가 생긴거 같다.🚨


Why?

운영체제 [OS] 마다 줄바꿈을 지정하는 문자열이 다른데, 이를 형상관리 해주는 Git이 어느 플랫폼의 방식을 선택해야 할 지 몰라서 Warning을 해준것이다.

 

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)
  • 커서를 다음라인 맨앞으로 옮겨주는 동작

How?

autocrlf 사용

  • 시스템 전체 적용하고 싶다면 --global 를 추가해준다.

CRLF > LF 변경

core.autocrlf = true

 

기본 설정
운영체제(OS) 상관없이 줄바꿈에 대한 문자열 그대로 인식해 저장하기!
(문제가 발생할 수 있음!)

core.autocrlf = false

 

LF를 line ending으로 사용한다.

core.autocrlf = input

Window

git config --global core.autocrlf true

 

Linux, Mac

git config --global core.autocrlf input

 

변환 기능을 사용하지 않고, 에러 메시지만 안뜨게 설정. (비추)

git config --global core.safecrlf false

 

 

'IT > Git & Github' 카테고리의 다른 글

[형상 관리] Git (정의, 설치, 초기 설정) - 1  (4) 2024.01.29
Git 브랜치  (0) 2023.06.04
Git 명령어 3  (0) 2023.06.04
Git 명령어 2  (0) 2023.06.01
Git 명령어 1  (0) 2023.06.01

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