티스토리 뷰

Language/JAVA

Java Array(배열) 만들고 출력하기

KyeongRok Kim 2018. 1. 16. 16:14

Java Array(배열) 만들고 출력하기

 

배열 기초

배열은 int[] 로 선언 합니다 그냥 변수는 int로 시작하는데 배열은 int뒤에 []가 붙습니다.

 

예를들어 학생 1명의 국어, 영어, 수학 성적이 차례대로 100, 99, 98일 때 이 점수를 배열에 저장 했다가 총점을 구하는 기능을 아래와 같이 만들 수 있습니다.

public static void main(String[] args) {
    int[] studentScore = {100, 99, 98};
    System.out.println(String.format("총점:%d", studentScore[0] + studentScore[1] + studentScore[2]));
}

결과

총점:297

 

2차원 배열 사용

앞에서는 학생 한명의 성적을 구했지만 이번에는 학생 5명의 성적을 배열에 저장했다가 구하고 싶을 수 있습니다.

이럴 때 2차원 배열을 이용합니다. 2차원 배열은 int[][]로 선언 합니다. 1차원 배열은 앞에서 int[]로 선언 했고 여기에 []를 하나 더 불여서 int[][]로 선언 합니다.

 

아래 예제는 학생 5명의 국어, 영어, 수학 점수를 배열에 저장하고 출력하는 예제 입니다.

public static void main(String[] args) {
    int[][] students = {
            {100, 99, 98},
            {99, 98, 97},
            {98, 98, 97},
            {97, 98, 97},
            {96, 98, 97},
    };

    for (int[] student : students) {
        System.out.println(String.format("국어:%d 영어:%d 수학:%d", student[0], student[1], student[2]));
    }
}

 

결과

국어:100 영어:99 수학:98
국어:99 영어:98 수학:97
국어:98 영어:98 수학:97
국어:97 영어:98 수학:97
국어:96 영어:98 수학:97

 

package com.named.sports.test;

import org.junit.Test;

public class ArrayTest {
    @Test
    public void name() throws Exception {
        int[][] ar = new int[3][3];

        ar[0][0] = 1;
        ar[0][1] = 2;
        ar[0][2] = 3;
        ar[1][0] = 4;
        ar[1][1] = 5;
        ar[1][2] = 6;
        ar[2][0] = 7;
        ar[2][1] = 8;
        ar[2][2] = 9;

        printMatrix(ar);

    }

    public void printMatrix(int[][] m){
        try{
            int rows = m.length;
            int columns = m[0].length;
            String str = "|\t";

            for(int i=0;i<rows;i++){
                for(int j=0;j<columns;j++){
                    str += m[i][j] + "\t";
                }

                System.out.println(str + "|");
                str = "|\t";
            }

        }catch(Exception e){System.out.println("Matrix is empty!!");}
    }
}
 

결과

| 1 2 3 |

| 4 5 6 |

| 7 8 9 |

https://stackoverflow.com/questions/5061912/printing-out-a-2-d-array-in-matrix-format

3*3 배열을 만들고 출력하는 소스코드이다.

int[][] ar2 = {
   {10, 20, 30},
   {40, 50, 60},
   {70, 80, 90}
};

 

중괄호를 쓰면 위 처럼 길게 안써도 짧게 쓸 수 있다.

 

자바 Array를 이용한 10개의 팀이 경기하는 경기 수 순열 만드는 로직

public class TeamPermu {
    private String[] teams = {"SS", "WO", "NC", "LG", "SK", "OB", "LT", "HT", "HH", "KT"};

    public ArrayList<String[]> permutation(){
        ArrayList<String[]> allCase = new ArrayList<>();

        for ( int i = 0 ; i < teams.length ; i++){
            for(int j = 0 ; j < teams.length ; j++){
                // {"SS", "WO"}를 append to allCase

                //두개가 같으면 넣지 않는다.
                if(teams[i] != teams[j]){
                    String[] item = new String[2];
                    item[0] = teams[i];
                    item[1] = teams[j];

                    allCase.add(item);
                }
            }
        }

        return allCase;
    }

    public static void main(String[] args) {
        ArrayList<String[]> allCase = new TeamPermu().permutation();
        //넣은 것 출력함
        for(String[] item : allCase){
            for(int i = 0 ; i < item.length ; i++){
                System.out.print(item[i]);
                System.out.print(" ");
            }
            System.out.println("");
        }
    }
}

 

결과

SS WO SS NC SS LG SS SK SS OB SS LT SS HT SS HH SS KT WO SS WO NC WO LG WO SK WO OB WO LT 

··· 생략 ···

 

이렇게 야구팀 10개(SS는 삼성 등)가 경기를 할 수 있는 가지수는 10P9 로 90개 되겠다.

 

 

알파벳 n글자로 만들 수 있는 모든 조합

예를들어 n이 2라면

AA, AB, AC ... BA, BB, BC ... ZA... ZZ

 

n이 3이라면

AAA, AAB, AAC ... BAA, BAB ... ZZA .. ZZZ

 

핵심 로직

n번만큼 depth로 들어가는 반복문이 만들어 져야 한다.

 

2 "" -> p(1, A) -> p(0, AA)

                    -> p(0, AB)

                    -> p(0, AC)

                    -> p(0, AD)

                    -> p(0, AE)

                    -> p(0, AF)

             ...

                    -> p(0, AZ)

      -> p(1, B)

      -> p(1, C)

      -> p(1, D)

      -> p(1, E)

      -> p(1, F)

....

      -> p(1, Z)

 

코드

public class Permutation {
    public void printStrings(int n, String prefix) {
        if(n == 0){
            System.out.println(prefix);
        } else {
            for (int i = 0; i < 26; i++) {
                printStrings(n - 1, prefix + (char) (i + 65));
            }
        }
    }
    public static void main(String[] args) {
        Permutation permutation = new Permutation();
        permutation.printStrings(2, "");
    }
}

 

 

 

end.

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함