ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] 배열, 배열 복사, 다차원 배열
    공부일지 2024. 3. 12. 17:45

     

    [배열] 182page

    : 같은 타입의 여러 변수를 하나의 묶음으로 다루는 것.

    ex. int [] score = new int[5]; - 0부터 시작되므로 0~4(index)까지의 5개의 int (length)을 저장할 수 있는 배열이 생성된다.

     

    [배열의 선언과 생성] 183page

    int[] score = new int[5]; // 배열의 선언과 생성을 동시에, 길이가 5int 배열

     

    [배열이 길이와 인덱스] 184page

    : 인덱스의 범위는 0부터 배열길이 1’까지

     

    #배열 선언하고 프린트하기

    더보기

    public class test03 {

     

         public static void main(String[] args) {

     

                int[] score = new int[4];

     

                score[0]=1;

                score[1]=2;

                score[2]=3;

                score[3]=4;

     

                // for(int i=0; i<5; i++)

                // for(int i=0; i<=score.length-1; i++)

                for(int i=0; i<score.length; i++) {

                      System.out.print("score"+"["+i+"]"+"="+score[i]+"\t");

                }

          }

    }

     

     

     

    [배열 복사]

    # 길이가 5개인 배열을 길이 10개로 변경하려고 할 때.

    10개의 새로운 배열 생성

    기존 배열의 값을 복사 (인덱스의 값을 옮겨주기, for문 사용) / 대입

    참조변수 변경 / 대입

     

    더보기

    public class test03 {

     

          public static void main(String[] args) {

     

                int[] score = new int[5];

     

                int[] nscore = new int[10];

     

                // 기존 배열

                for (int i=0; i<score.length; i++) {

                      score[i] = (i+1)*10;

                      System.out.println(score[i]);

                }

     

                // 새로운 배열 setting

                for(int i=0; i<score.length; i++) {

                      nscore[i] = score[i];

                }

     

                // 참조변수 score 길이가 1인 배열에 접근할 수 있음

                score = nscore;

     

                for(int i=0; i<score.length; i++) {

                      System.out.printf("변경 후 => score[%d]=%d \n", i, score[i]);

                 }

           }

    }

     

     

     

    # 배열에 저장된 값으로 총점, 평균 구하기

     

    더보기

    public class test03 {

     

          public static void main(String[] args) {

     

                int[] score = {100,64,88,29,94};

                int sum = 0; // 총점

                float avg = 0; // 평균

     

                for(int i=0; i<score.length; i++) {

                      sum+=score[i];

                }

     

                avg=sum/(float)score.length;

     

                System.out.printf("총점은 %d입니다.", sum);

                System.out.printf("평균은 %.2f입니다.", avg);

          }

    }

     

     

     

    # 배열의 최대값, 최소값 print하기

    더보기

    public class test03 {

     

          public static void main(String[] args) {

     

                int[] score = {79,88,91,33,100,55,95};

                int max = score[0]; // 최대값

                int mini = score[0]; // 최소값

     

                for(int i=0; i<=score.length-1; i++) {

                      if(max<score[i]) {

                            max=score[i];

                      }

     

                      if(mini>score[i]) {

                            mini=score[i];

                      }

                }

                System.out.printf("배열 score의 최대값은 %d 최소값은 %d입니다.", max, mini);

          }

    }

     

     

     

    # 길이가 7arr 배열에 1~10 사이의 수를 랜덤으로 저장, 짝수만 출력

    더보기

    public class test03 {

     

          public static void main(String[] args) {

     

                int[] arr = new int[7];

     

                for(int i=0; i<arr.length; i++) {

                      int a = (int)(Math.random()*10)+1;

     

                      arr[i]=a;

     

                      if(arr[i]%2==0) { // 인덱스 값이 짝수인것만 출력

                            System.out.printf("arr[%d]=%d \n",i, arr[i]);

                      }

                }

          }

    }

     

     

    # 길이가 10인 배열에 0~9까지의 수를 저장, 100번 섞기, 배열의 순서가 랜덤하게 출력되도록 구현. 197page

    * (int)(Math.random()*10) //0~9까지

    * (int)(Math.random()*9)+1 //1~9까지

     

    더보기

    public class test03 {

     

          public static void main(String[] args) {

     

                // 길이가 10인 배열 생성, 인덱스값:0~9

                int[] numArr = {0,1,2,3,4,5,6,7,8,9};

     

                //100번 섞기

                for(int i=0; i<100; i++) {

                      int n = (int)(Math.random()*10);

     

                      int tmp = numArr[0];

                      numArr[0] = numArr[n];

                      numArr[n] = tmp;

                }

     

                for(int i=0; i<numArr.length; i++) {

                      System.out.println(numArr[i]);

                }

          }

    }

     

     

     

    # 로또 번호 만드는 프로그램. 199page

    - 길이 45개인 배열에 1~45 숫자 Setting

    랜덤 indexi index에 있는 값을 교환

    6개의 값을 뽑아서 출력(0~5 index)

    더보기

    public class test03 {

     

          public static void main(String[] args) {

     

                int[] num = new int[45];

     

                for(int i=0; i<num.length; i++) {

                      num[i]=i+1;

                }

     

                for(int i=0; i<6; i++) {

                      int x = (int)(Math.random()*45);

     

                      int tmp = num[i];

                      num[i] = num[x];

                      num[x] = tmp;

                }

     

                for(int i=0; i<6; i++) {

                      System.out.printf("%d \t", num[i]);

                }

          }

    }

     

     

     

    [다차원 배열] 214page

    # 2차원 배열을 출력하고 총합을 구하는 코드

    더보기

    public class test03 {

     

          public static void main(String[] args) {

     

                int[][] score = {

                                        {100,100,100},

                                        {20,20,20},

                                        {30,30,30},

                                        {40,40,40}

                                        };

                int sum = 0;

     

                for(int i=0; i<score.length; i++) {

     

                      for(int j=0; j<score[i].length; j++) {

                            System.out.printf("score[%d][%d]=%d\t", i, j,score[i][j]);

                            sum += score[i][j];

                      }

                      System.out.println();

                }

                System.out.println("2차원 배열 score에 저장된 값의 총합은 "+sum+"입니다.");

          }

    }

     

     

     

    * score.lengthscore[i].length의 차이점

      score[0][0] score[0][1] score[0][2]  
    score[0] 100 100 100  
      score[1][0] score[1][1] score[1][2] score[1][3]
    score[1] 50 50 50 50

    해당 2차원 배열에서 score.length2(0~1)가 되고, score[1],length4(0~3)가 된다.

     

     

     

    # 성적표 출력

    더보기

    public class test03 {

     

          public static void main(String[] args) {

     

                int[][] score = {

                {20,20,20},

                {30,30,30},

                {40,40,40},

                {50,50,50},

                };

     

                int num = 1;

                int sum = 0;

                float avg = 0;

     

                System.out.printf("번호\t국어\t영어\t수학\t총점\t평균");

                System.out.println();

     

                for(int i=0; i<score.length; i++) {

                      System.out.printf("%d\t", num);

                      num++;

     

                      for(int j=0; j<score[i].length; j++) {

                            System.out.printf("%d\t",score[i][j]);

                            sum+=(score[i][j]);

                            avg=sum/(float)score[i].length;

                      }

                      System.out.printf("%d\t%.1f", sum, avg);

                      System.out.println();

                      sum=0;

                }

     

                System.out.println("=================================================");

                System.out.print("총점\t");

     

                int sum2 = 0;

     

                for(int i=0; i<3; i++) {

                      for(int j=0; j<4; j++) {

                            sum2+=score[j][i];

                      }

                      System.out.printf("%d\t", sum2);

                      sum2=0;

                }

          }

    }

Designed by Tistory.