본문 바로가기
Programming/Java

[Java] - 배열

by 구튼탁 2020. 10. 29.
728x90
import java.util.Arrays;

public class ArrayInitialize {
    public static void main(String[] args) {

        int arr[] = new int[]{1,2,3,4,5};
        for(int dat : arr){
            System.out.println(dat);
        }
        //배열 요소 쉽게 출력하기.
        System.out.println(Arrays.toString(arr));

        char arr2[] = {'a', 'b', 'c'};

        System.out.println(arr); // 참조변수 arr의 값

        System.out.println(arr2); // char타입의 배열만 출력 결과가 다름. abc

        // 배열의 복사 1.for문 이용
        int tmp [] =new int[arr.length * 2];
        for (int i= 0; i < arr.length; i++){
            tmp[i] = arr[i];
        }
        System.out.println(Arrays.toString(tmp));

        // 배열의 복사 2. System.arraycopy()

        char word1 [] = new char[] {'a', 'b', 'c', 'd', 'e'};
        char word2 [] = new char[] {'가', '나', '다', '라', '마'};
        char result [] = new char[word1.length + word2.length];

        System.arraycopy(word1, 0, word2, 1, 2);
        //word1 배열에서 0번 부터 2개를 복사해서 word2의 인덱스 2부터 2개 변경
        System.out.println(word2);

        //최댓값 최솟값
        int random [] = new int[5];
        for(int i = 0; i < random.length; i++){
            random[i] = (int)(Math.random() * 100) + 1;
        }
        System.out.println(Arrays.toString(random));

        int max = random[0];
        int min = random[0];
        for (int i = 1; i < random.length; i++){

            if (random[i] > max){
                max = random[i];
            }
            if(random[i] < min){
                min = random[i];
            }
        }

        //1 ~10 숫자 무작위 추출
        int nums [] = {1,2,3,4,5,6,7,8,9,10};
        for(int i = 0; i < 100; i++){
            int index = (int)(Math.random()*10);

            int temp = nums[0];
            nums[0] = nums[index];
            nums[index] = temp;
        }

        for(int dat : nums){
            System.out.print(dat);
        }
    }
}
728x90

댓글