Java

04.20 - 배열

amungstudy 2023. 4. 20. 15:58

package array;

 

import java.util.Scanner;

 

/**

*

* @author admin

* @since 20230420_01

* @apiNote 배열의 정의

* {@summary}

* 배열(array) 데이터를 저장, 수정, 삭제, 관리하기 위한 자료구조의 일종

* ex) 자료구조 - 데이터를 효율적으로 저장하고 조작하기 위한 방법을 정의한 것.

* 배열의 특징

* -동일한 자료형의 데이터를 순차적으로 나열한 것

* -각 데이터는 배열의 인덱스(index)라는 숫자로 구분

* -인덱스 번호는 처음 삽입된 데이터를 0으로 1씩 순차적으로 증가함.

* -배열의 마지막 인덱스 번호는 배열의 크기 -1 이 됨.

*/

public class UseArrayExample {

 

public static void main(String[] args) {

 

// 배열 생성 방법

// 1. 배열 생성 전 저장할 값이 정해져 있을 경우

int [] array = new int[] {80,70,60,50,90};

//2. 선언과 동시에 값을 지정할때는 new 연산자 생략 가능

int array2[] = {80,70,60,50,90};

 

//3. 선언이 이루어지고 난 다음에 초기화 //new 연산자를 이용해야함.

int[] array3 = null;

array3 = new int[]{80,70,60,50,90};

 

//4. 생성 시 값이 정해져 있지 않을 경우

// 저장할 공간만 생성 가능

//생성된 공간에는 기본값으로 자동 초기화

int[] array4 = new int[5];

// int type의 데이터 5개를 저장할 공간을 확보

// 배열의 원소에 접근할때는 인덱스 번호를 사용

// index == 0 1 2 3 4

// array4 == [0][0][0][0][0];

System.out.println(array4);

// array4배열의 0번째 인덱스에 저장된 원자값을 호출

int a = array4[0];

System.out.println(a);

array4[1] = 10;

// index == 0 1 2 3 4

// array4 == [0][10][0][0][0];

array4[2] = 70;

array4[3] = 80;

array4[4] = 70;

// index == 0 1 2 3 4

// array4 == [0][10][70][80][70];

 

//인덱스를 벗어난 번호의 공간은 존재하지 않음으로 오류 발생

//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 1

//array4[-1] = 100;

//array4[5] = 100;

 

//타입이 일치하지 않는 값의 대입은 컴파일 시 오류 발생

// array4[0] = 40.1;

 

//5. 배열의 길이 == 크기

// 주소를 전달받아 사용하는 경우가 많으므로 배열의 크기를 알려주는 read only 변수가 존재

int length = array4.length;

//배열의 크기는 변할 수 없으므로 읽기만 가능하다.

// array4.length = 10;

 

// 6. 배열의 장점

// 연관성이 있는 데이터를 순차적으로 나열하고

// 순차접근이 가능한 인덱스 번호를 제공함으로

// 반복문으로 각 데이터에 순차적인 접근이 용이하다.

 

// 1. 학생의 점수를 저장하고 평균을 구한다.

int scoreChoi = 100;

int scoreKim = 70;

int scoreLee = 80;

int sum = scoreChoi+scoreKim+scoreLee;

double avg = sum/3.0;

 

// 2. 배열을 이용한 연산

int[] scores = null;

//import

Scanner sc = new Scanner(System.in);

System.out.println("점수를 등록할 학생 수를 입력하세요 > ");

int studentCount = sc.nextInt();

System.out.println(studentCount+"명의 학생 점수를 입력해주세요");

scores = new int[studentCount];

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

System.out.println((i+1)+"번째 학생의 점수를 입력해주세요 >");

scores[i] = sc.nextInt();

 

}

sum = 0;

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

sum +=scores[i];

}

avg = sum/scores.length;

System.out.println(avg);

 

 

//위랑 같은 코드

scores = new int[] {90,80,70,};

sum = 0;

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

sum+= scores[i];

}

 

avg = sum/scores.length;

}

 

}

 


package array;

 

/**

*

* @author admin

* @since 20230420_03

* @apiNote 배열 타입 및 참조 타입

*/

public class ArrayRefExample {

 

public static void main(String[] args) {

int[] arrays = null;

//일단 null먼저 만들고 나중에 초기화 되어 있는지 null값 체크 후 사용 : ==,!=연산 가능.

if(arrays !=null) {

arrays[0] = 10;

}else { (null -> 참조하는 값이 없다. 초기화전이다. 연산에서 사용이 불가능하다.  ) -> 이거 가지고 사용하면 NullpointException 오류 발생함.

arrays=new int[6];

}

 

arrays[arrays.length-1] = 100;

 

// Character type의 배열

// 알파벳 == 몇자? == 26자

char chars[] = new char[26];

char start = 'A'; // 'A' == 65

 

// 쉼표 기준으로 나열하면 여러가지 적용 가능하다. (여기서는 증감식 2개)

for(int i=0; i<chars.length;i++,start++) {

chars[i] = start;

}

 

//향상된 for문 (인덱스 번호 활용안하고 값만 필요할때 사용)

// 0번째 인덱스부터 배열의 크기만큼 순차적으로 값을 읽어와

// 변수에 저장

// for(꺼내온 원자값을 저장할 변수 : 값이 저장된 배열){}

for(char c: chars) {

System.out.print(c+" ");

}

System.out.println();

// 일반 for문

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

System.out.print(chars[i]+" ");

}

System.out.println();

// 실수 타입

double[] doubles = new double[3];

doubles[0] = 3.14;

for(double d : doubles) {

System.out.print(d + " ");

}

 

// 논리 타입 - 초기값 : false

boolean[] tasks = new boolean[5];

System.out.println(tasks[tasks.length-1]);

 

// 참조 타입 - 주소값을 저장하는 배열

String[] strs = new String[3];

 

for(String s : strs) {

System.out.print(s + " ");

}

 

// 참조타입 배열 - 배열을 저장하는 배열

// int[][] arrays2 = null;

// int[] arrays2[] = null;

int arrays2[][] = {

{5,8,9}, //arrays2[0]

{6,7,8,9}, //arrays2[1]

{1,2,3} //arrays2[2]

};

//이차원 배열 arrays2의 길이

System.out.println(arrays2.length);

System.out.println(arrays2);

System.out.println(arrays2[0]);

System.out.println(arrays2[1]);

System.out.println(arrays2[2]);

 

System.out.println(arrays2[0].length);

System.out.println(arrays2[1].length);

System.out.println(arrays2[2].length);

 

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

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

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

System.out.println(arrays2[i][j]);

}

}

 

//공간만 확보하는 경우 : [3개 배열][정수값이 3개] : 고정된 크기를 가진다.

// int[][] arrays3 = new int[3][3];

//아래와 같이 생략할 수 있다. : 고정된 크기를 가지지 않음.

int[][] arrays3 = new int[3][];

arrays3[0] = new int[3];

arrays3[0] = new int[5];

arrays3[0] = new int[2];

}

}


package array;

 

import java.util.Arrays;

import java.util.Scanner;

 

/**

*

* @author admin

* @since 20230420_04

* {@summary} 1차원배열 활용 실습 과제

*/

public class StudentExample {

 

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

 

//학생 점수를 입력받아 저장할 배열

int[] scores = null;

//학생 수를 저장할 변수

int studentNum = 0;

 

//반복문 탈출 flag

boolean isRun = true;

 

while(isRun) {

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

System.out.println("1.학생수|2.점수입력|3.전체점수|4.분석|5.종료");

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

System.out.println("선택하실 기능의 번호를 입력하세요 > ");

 

/*

* 1. 학생 수를 입력받아 점수를 저장할 수 있는 배열 생성

* 2. 생성된 배열 크기(학생수)만큼 점수를 입력받아 배열에 순차적으로 저장

* 3. 배열에 저장된 전체 학생의 점수 출력

* 4. 분석 - 배열에 저장된 점수를 이용하여 (총점,최고점수,최저점수,평균)출력

* 5. 프로그램 종료

*/

 

int sum = 0;

boolean isUse = sc.hasNextInt();

if(!isUse) {

System.err.println("숫자를 입력해주세요");

sc.next();

}else {

int selectNum = sc.nextInt();

switch(selectNum) {

case 1:

 

System.out.println("총 학생수를 입력하세요 > ");

studentNum = sc.nextInt();

scores = new int[studentNum];

break;

case 2:

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

System.out.println((i+1)+"번째 학생의 점수를 입력해주세요 > ");

scores[i]=sc.nextInt();

}

break;

 

case 3:

for(int score:scores) {

sum+=score;

}

System.out.printf("전체 학생의 점수는 %d점 입니다.\n",sum);

break;

case 4:

for(int score:scores) {

sum+=score;

}

double avg = (double)sum/scores.length;

int max = 0;

int min = scores[0];

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

if(scores[i]<scores[i+1]) {

max = scores[i+1];

}else {

max = scores[i];

}

}

 

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

if(min<=scores[i]) {

continue;

}else {

min = scores[i];

}

}

System.out.printf("총점수는 %d점 입니다.\n",sum);

System.out.printf("최고점수는 %d점 입니다.\n",max);

System.out.printf("최저점수는 %d점 입니다.\n",min);

System.out.printf("평균 점수는 %.2f점 입니다.\n",avg);

break;

case 5:

System.out.println("프로그램을 종료합니다.");

isRun = false;

break;

}

}

}

}

}

 

 


1차원배열 활용 실습 과제 - 선생님 풀이

*/

public class StudentExample2Copy {

 

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

 

// 학생 점수를 입력받아 저장할 배열

int[] scores = null;

// 학생 수를 저장할 변수

int studentNum = 0;

// 반복문 탈출 flag

boolean isRun = true;

 

a : while(isRun) {

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

System.out.println("1.학생수|2.점수입력|3.전체점수|4.분석|5.종료");

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

System.out.println("선택하실 기능의 번호를 입력하세요 > ");

/*

1. 학생 수를 입력받아 점수를 저장할 수있는 배열 생성

2. 생성된 배열 크기(학생수)만큼 점수를 입력받아 배열에 순차적으로 저장

3. 배열에 저장된 전체 학생의 점수 출력

4. 분석 - 배열에 저장된 점수를 이용하여 (총점,최고점수,최저점수,평균)출력

5. 프로그램 종료

*/

int selectNo = sc.nextInt();

System.out.printf("선택하신 번호는 %d입니다. %n",selectNo);

 

if(selectNo != 1 && selectNo != 5 && scores == null) {

System.out.println("학생 수를 먼저 입력해 주세요.");

continue;

}

 

switch(selectNo) {

case 1 :

System.out.println("학생 수를 입력해 주세요 > ");

// 입력 받은 학생 수를 변수에 저장

studentNum = sc.nextInt();

scores = new int[studentNum];

System.out.println("등록된 학생수는 : " + scores.length);

break;

case 2 :

System.out.println("점수 입력");

// 배열의 크기만큼 순회 하면서 각 index에 사용자가 입력한

// 점수를 저장

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

System.out.println((i+1)+"번째 학생의 점수를 입력하세요 > ");

scores[i] = sc.nextInt();

}

System.out.println("점수 입력 완료");

break;

case 3 :

System.out.println("학생들의 점수 출력");

for(int score : scores) {

System.out.println("등록된 학생의 점수는 : " + score);

}

break;

case 4 :

System.out.println("학생들의 점수 분석");

// 전체총점, 최저점수, 최고점수, 평균점수

int sum = 0;

double avg = 0;

int max, min;

max = min = scores[0]; //배열의 임의값을 넣어줘서 비교하게 한다.

// 50 90 70

for(int i : scores) {

sum += i;

if(max < i) max = i;

if(min > i) min = i;

}

avg = sum / (double)studentNum;

System.out.println("총점 : " + sum);

System.out.printf("평균 : %.1f %n" , avg);

System.out.println("최고점수 : " + max);

System.out.println("최저점수 : " + min);

break;

case 5 :

System.out.println("종료");

isRun = false;

break a;

}

 

}

 

}

 

}

 


Math.random()함수를 이용하여 6개의 당첨번호를 생성

* 사용자에게 로또 번호 6개를 입력받아 당첨번호와 비교하여 등수를 출력

* {@summary}

* 1~45까지의 중복되지 않는 랜덤한 값 6개와 보너스 번호를 비교하여

* 사용자가 선택한 6개의 번호를 비교, 등수를 출력하는 프로그램

*

* */

public class LottoProgram {

 

public static void main(String[] args) {

// luckyNum == 당첨 번호

/*

// 0~0.99999 // 0 ~ 1미만의 실수형 난수를 출력하는 함수

double random = Math.random();

System.out.println(random);

// 필요한 난수 == 1~45

int num = (int)(Math.random()*45)+1;

System.out.println(num);

*/

 

int[] luckyNum = new int[6];

int count =0;

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

count++;

luckyNum[i] = (int)(Math.random()*45)+1;

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

//중복처리

if(luckyNum[i] == luckyNum[j]) {

i--; //1빼고 다시 올라가서 중복 안되게 함.

break;

}

}

}

System.out.println(count);//총 돌린 횟수 확인용

 

//배열에 저장된 정수값을 오름차순으로 정렬하여 저장

int temp = 0;

// 0 1 2 3 4 5

// [19][18][43][1][13][25]

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

// luckyNum[i]

for(int j = i + 1; j <luckyNum.length; j++) {

// 앞 인덱스에 큰 값이 존재하면 뒤 인덱스에 값과

// 위치를 변경하여 오름차순 구현

if(luckyNum[i] > luckyNum[j]) { // > :오름차순 <:내림차순

// swap

temp = luckyNum[i];

luckyNum[i] = luckyNum[j];

luckyNum[j] = temp;

}

}

}

 

// 보너스 번호

int bonus = (int)(Math.random()*45)+1;

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

if(bonus == luckyNum[i]) {

bonus = (int)(Math.random()*45)+1;

// 0 번째 인덱스부터 다시 비교할 수 있도록 i값을 -1로 재할당

i = -1;

// i -=1;

}

}

 

//당첨번호 출력

/*

for(int i : luckyNum) {

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

 

}

System.out.println();

*/

 

//나의 로또 번호

int[] myLotto = new int[6];

boolean isRun = true;

Scanner sc = new Scanner(System.in);

while(isRun) {

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

System.out.println("1.로또구입|2.내번호확인|3.당첨확인|4.종료");

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

System.out.println("선택할 항목의 번호를 입력하세요 > ");

int selectNo = sc.nextInt();

 

switch(selectNo) {

case 1:

System.out.println("로또 구입");

a : for(int i=0; i< myLotto.length;i++) {

System.out.println((i+1)+"번째 번호 입력 > ");

int num = sc.nextInt();

//번호 범위 벗어나는 수 처리. 배열에 수 넣지 않고 반복문으로 돌아감.

if(num <1 || num >45) {

System.out.println("1~45사이의 번호를 입력");

i-=1; //잘못 입력한 자리에 다시 값 입력받게 함.

continue;

}

//중복 제거

// 현재 등록하려는 번호보다 먼저 등록된 번호중에

// 중복이 있는지 확인

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

if(num == myLotto[j]) {

System.out.println("이미 등록된 번호입니다.");

i--;

continue a;

}

}

 

myLotto[i] = num;

}

break;

case 2:

System.out.println("내 번호 확인");

for(int lotto : myLotto) {

System.out.printf("[%d]",lotto);

}

//줄바꿈 추가

System.out.println();

break;

case 3:

System.out.println("당첨 확인");

//당첨번호 출력 및 일치하는 번호의 수로 등수 출력

System.out.print("당첨번호 : ");

for(int lotto : luckyNum) {

System.out.printf("[%d]",lotto);

}

System.out.println();

System.out.print("나의번호 : ");

for(int lotto : myLotto) {

System.out.printf("[%d]",lotto);

}

System.out.println();

 

//일치하는 개수 확인

int cnt = 0; // 일치하는 번호 개수

// 보너스 번호가 일치하는지 확인

boolean isBonus = false;

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

for(int j = 0; j < myLotto.length; j++) {

if(myLotto[i] == bonus) {

isBonus = true;

}

if(luckyNum[i] == myLotto[j]) {

cnt++;

}

}

}

System.out.println("일치하는 번호 개수 : " + cnt);

 

if(cnt == 6) {

System.out.println("1등 입니다.");

}else if(cnt == 5) {

if(isBonus) {

System.out.println("2등 입니다.");

}else {

System.out.println("3등 입니다.");

}

}else if(cnt == 4) {

System.out.println("4등 입니다.");

}else if(cnt == 3) {

System.out.println("5등 입니다.");

}else {

System.err.println("꽝!");

}

 

 

break;

default :

System.out.println("종료");

isRun = false;

} // switch end

} // while end

} // main end

}