Java 상수 배열 - Java sangsu baeyeol

상수

final [자료형] [변수명] = [초기값];

당연하지만 상수이므로 선언 이후 값 변경 안됨

배열

  • 같은 자료형끼리의 묶음으로 처리할 수 있는 자료형이다
  • 배열은 선언되는 타입에 관계없이 무조건 객체로 인식된다
  • 배열은 레퍼런스 변수이다
  • 목적 : 일괄적인 데이타 처리

일차원배열

  • 선언하는법

int []arr = {2, 3, 4, 5} //선언하면서바로초기값을넣어주는경우(자동으로4개로할당) int []arr; //일단선언후 arr = new int[4]; //필요시메모리할당후사용하면됨 int []arr = new int[4] //선언후바로메모리할당 arr[0] = 10; //0번지에10을할당

  • 배열의속성: length : 길이를 가지는 속성 예) arr.length => 4가 나옴

package test.day0408; public class ArrayEx2 { public static void main(String[] args) { // TODO Auto-generated method stub int arr[] = {3,5,6,7}; System.out.println(arr.length); System.out.println(arr[1]); //for문으로 출력하기 - 1 for(int i = 0 ; i < arr.length ; i++ ) { System.out.println("arr[" + i + "] : " + arr[i]); } //for문으로 출력하기 -2 for(int a:arr) { //자동으로 갯수만큼 반복 System.out.println(a); } //값 변경 arr[2] = 100; System.out.println(arr[2]); } }

실습문제

배열 선언 후 몇개를 입력할지 입력 받고 메모리 할당받기

package test.day0408; import java.util.Scanner; public class TestEx4 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int num = 0; System.out.println("배열 갯수를 입력해주세요."); num = sc.nextInt(); int arr[] = new int[num]; for(int i=0 ; i < arr.length ; i++) { System.out.println("arr[" + i + "] : " + arr[i]); } } }

여러개의 숫자를 배열에 담은 후 그 중 가장 큰 수와 작은 수 구하기

package test.day0408; public class TestEx5 { public static void main(String[] args) { // TODO Auto-generated method stub int arr[] = { 5, 1, 3, 10, 20 }; int max = arr[0]; int min = arr[0]; for(int i=0 ; i < arr.length ; i++ ) { if(arr[i] > max) { max = arr[i]; }else if(arr[i] < min){ min = arr[i]; } } System.out.println("max : " + max + ", min : " + min); } }

30개의 점수를 배열에 저장 후 각 점수 분포도를 구하시오

예) 갯수를 구하기 위한 배열 11개짜리 선언 후

0번지 : 0점 인원수 저장

1번지 : 10~19점 저장

.

.

9번지 : 90~99저장

10번지 : 100점만 저장

package test.day0408; public class TestEx6 { public static void main(String[] args) { // TODO Auto-generated method stub int score[] = new int[30]; for(int i = 0 ; i < 30 ; i++) { score[i] = (int)(Math.random()*101); System.out.println("score["+i+"] : "+score[i]); } int table[] = new int[11]; for(int i = 0 ; i < score.length ; i++) { table[(score[i]/10)]++; } for(int i = 0 ; i < table.length ; i++ ) { if(i!=10) { String s = i + "0 ~ " + i + "9"; System.out.printf("%-10s", s); }else { System.out.printf("%-10s", "100!!!!"); } } System.out.println(); for(int i = 0 ; i < table.length ; i++ ) { System.out.printf("%-10s", " " + table[i]); } } }

영어 문장을 길~게 입력 후 엔터를 누르면 알파벳의 분포도가 나오게…

package test.day0408; import java.util.Scanner; public class TestEx7 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String msg =""; System.out.println("영문 문장을 입력해주세요."); msg = sc.nextLine(); int num[] = new int['Z' - 'A' + 1]; System.out.println(msg.length()); for( int i = 0 ; i < msg.length() ; i++ ) { char ch = msg.charAt(i); if(ch>='a' && ch<='z') { num[msg.charAt(i) - 'a']++; }else if(ch>='A' && ch<='z') { num[msg.charAt(i) - 'A']++; } } for( int i = 0 ; i < num.length ; i++) { if(num[i]!=0) System.out.println((char)(i+'A') + "의 갯수: " + num[i]); } } }

5명의 점수를 입력시 등수를 구하시오(단 동점일경우에는 동순위 부여)

package test.day0408; import java.util.Scanner; public class TestEx8 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int score[] = new int[5]; int grade[] = {5, 5, 5, 5, 5}; System.out.println("5명의 점수를 입력하세요."); for(int i = 0 ; i < score.length ; i++ ) { System.out.print(i+1 + "번째 학생의 점수> "); score[i] = sc.nextInt(); } for(int i = 0 ; i < score.length ; i++ ) { for(int j = 0 ; j < score.length ; j++ ) { if(score[i] > score[j]) { grade[i]--; } }System.out.println(i+1 + "번째 학생의 등수는 " + grade[i] + "등 입니다."); } } }

3명의 이름과 각각의 국,영,수 점수를 입력받은 후 이름 국어 영어 수학 총점 평균 등수 순으로 출력하시오

package test.day0408; import java.util.Scanner; public class TestEx9 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String name[] = new String[3]; int kor[] = new int[3]; int eng[] = new int[3]; int mat[] = new int[3]; int tot[] = new int[3]; int rank[] = {3, 3, 3}; double avg[] = new double[3]; for(int i = 0 ; i < kor.length ; i++ ) { System.out.println(i+1 + "번째 학생의 이름>"); name[i] = sc.nextLine(); System.out.println(i+1 + "번째 학생의 국어점수>"); kor[i] = sc.nextInt(); System.out.println(i+1 + "번째 학생의 영어점수>"); eng[i] = sc.nextInt(); System.out.println(i+1 + "번째 학생의 수학점수>"); mat[i] = sc.nextInt(); tot[i] = kor[i] + eng[i] + mat[i]; avg[i] = tot[i]/3.0; sc.nextLine(); } for(int i= 0 ; i < kor.length ; i++ ) { for(int j=0 ; j < kor.length ; j++) { if(avg[i] > avg[j]) { rank[i]--; } } } for(int i=0 ; i < kor.length ; i++) { System.out.printf("이름 %7s | 국어 %d | 영어 %d | 수학 %d | 총점 %3d | 평균 %5.1f | 등수 %d \n", name[i], kor[i], eng[i], mat[i], tot[i], avg[i], rank[i]); } } }

선택정렬

package test.day0408; public class SortingEx11 { public static void main(String[] args) { // TODO Auto-generated method stub int arr[] = {4,3,1,5,2}; int temp; //선택정렬 for(int i=0 ; i < arr.length-1 ; i++ ) { for(int j = i+1 ; j < arr.length ; j++) { if(arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for(int i=0 ; i < arr.length ; i++) { System.out.println("arr[" + i + "] = " + arr[i]); } } }

문자열 비교

package test.day0408; public class StringSortEx13 { public static void main(String[] args) { // TODO Auto-generated method stub String s[] = {"apple", "banana", "peach", "kiwi", "orange", "mange"}; String temp = ""; for( int i = 0 ; i < s.length-1 ; i++ ) { for(int j = i+1 ; j < s.length ; j++) { if(s[i].compareTo(s[j])>0) { temp = s[i]; s[i] = s[j]; s[j] = temp; } } } for( int i=0 ; i < s.length ; i++) { System.out.println("s[" + i + "]: " + s[i]); } } }

실습문제

  1. 문자열배열에 20명정도의 이름을 저장해두고검색 로직을 통해 이름 입력시 해당 이름이 몇번째에 있는지 출력하고, 만약 없다면 없다고 출력하시오

package test.day0409; import java.util.Scanner; public class testEx1 { public static void main(String []arr) { String names[] = {"alice", "bob", "chris", "david", "eva", "flin", "gwen", "heidi", "iren", "jackson", "kay","lisa","north","may","ori","pi"}; Scanner sc = new Scanner(System.in); String search; char restart = 'Y'; int hasName = 0; while(restart == 'Y'|| restart == 'y'){ System.out.println("검색할 이름>"); search = sc.nextLine(); hasName = 0; for(int i = 0 ; i < names.length ; i++ ) { if(search.equalsIgnoreCase(names[i])) { System.out.println(search + "는 " + i + "번째에 있습니다."); hasName = 1; } } if(hasName != 1) System.out.println("해당 이름이 없습니다."); System.out.println("다시 검색할까요? Y/N"); restart = sc.nextLine().charAt(0); } } }

  1. 성을 입력하면 해당 성씨가 몇명이 있는지 출력 (해당 이름도 함께 출력)

package test.day0409; import java.util.Scanner; public class ArrayNameSearchEx2 { public static void main(String[] args) { // TODO Auto-generated method stub String names[] = {"김기동","홍길동","김성규","이희진","박보검","박건영","최순실","최삡뺩","박정석","김두루미"}; Scanner sc = new Scanner(System.in); String search; char restart = 'Y'; int hasName = 0; while(hasName == 0) { System.out.println("검색할 성을 입력하세요."); search = sc.nextLine(); for(int i = 0 ; i < names.length ; i++ ) { if(names[i].startsWith(search)) { System.out.println(names[i]); hasName = 1; } } if(hasName != 1) System.out.println(search+"(으)로 시작하는 이름이 없습니다."); } } }

  1. 10개짜리 변수에 1~30 사이의 값을 중복없이 랜덤하게 넣어주기

package test.day0409; public class ArrayOverlapEx3 { public static void main(String []arg) { int nums[] = new int[10]; int num; for(int i = 0 ; i < nums.length ; i++) { boolean isOverlap = false; do{ isOverlap = false; nums[i] = (int)(Math.random()*30)+1; for(int j = 0 ; j < i ; j++ ) { if(nums[i] == nums[j]) isOverlap = true; } }while(isOverlap); System.out.println("nums[" + i + "] = " + nums[i]); } //Math.random()*(Max-min+1) +min } }

  1. 로또 만들기

package test.day0409; import java.util.Scanner; public class LottoEx4 { public static void main(String[] args) { // TODO Auto-generated method stub int lotto[] = new int[6]; boolean isOverlap = false; Scanner sc = new Scanner(System.in); int money; int round; System.out.println("금액을 입력해주세요"); money = sc.nextInt(); round = money/1000; if(round <= 0) { System.out.println("금액이 부족합니다."); }else { for ( int k = 0 ; k < round ; k++) { System.out.print(k+1 + "회 : "); for( int i = 0 ; i < lotto.length ; i++ ) { do { isOverlap = false; lotto[i] = (int)(Math.random()*45)+1; for( int j = 0 ; j < i ; j++ ) { if(lotto[i]==lotto[j]) isOverlap = true; } }while(isOverlap); } for(int i=0 ; i < lotto.length-1 ; i++ ) { int temp; for(int j = i+1 ; j < lotto.length ; j++) { if(lotto[i] > lotto[j]) { temp = lotto[i]; lotto[i] = lotto[j]; lotto[j] = temp; } } } for(int i=0 ; i < lotto.length ; i++) System.out.printf("%4d",lotto[i]); System.out.println(); } } } }

2차원 배열

  • 행과 열로 저장하고자 할 때 사용

int arr[][] = new int[2][3]; //2행3열인 배열 생성 arr.length //행의 갯수 arr[0].length //0번 행의 열의 갯수

  • 주로 퍼즐게임, 바둑, 오목 류의 행과 열로 데이타를 저장하는 경우에 사용

  • 행마다 열갯수가 다르게 만들 수도 있다

실습문제

3행 3열의 2차원 배열을 생성 후 1~3 사이의 난수를 넣음

가로, 세로, 대각선을 비교하여 같은 숫자가 한줄이라도 나오면 “빙고” 라고 출력

package test.day0409; public class BingoEx7 { public static void main(String[] args) { // TODO Auto-generated method stub int arr[][] = new int[3][3]; int isBingo = 0; //1~3사이의 랜덤값 넣 for(int i = 0 ; i < arr.length ; i++ ) { for( int j = 0 ; j < arr[i].length ; j++ ) { arr[i][j] = (int)(Math.random()*3)+1; } } //새로 해보기 for(int i = 0 ; i < arr.length ; i++) { if(arr[i][0] == arr[i][1] && arr[i][0] == arr[i][2]) isBingo++; } for(int i = 0 ; i < arr.length ; i++) { if(arr[0][i] == arr[1][i] && arr[0][i] == arr[2][i]) isBingo++; } //대각선 비교 새로 int cross1[] = new int[arr.length]; int cross2[] = new int[arr.length]; for( int i = 0 ; i <arr.length ; i++) { for( int j = 0 ; j < arr.length ; j++) { if( i == j) { cross1[i] = arr[i][j]; } if ( i+j == 2) { cross2[i] = arr[i][j]; } } } if(cross1[0] == cross1[1] && cross1[0] == cross1[2]) { isBingo++; System.out.println("cross1빙고"); } if(cross2[0] == cross2[1] && cross2[0] == cross2[2]) { isBingo++; System.out.println("cross2빙고"); } for(int i=0 ; i <arr.length ; i++) { for(int j=0 ; j<arr[i].length ; j++) { System.out.print("arr[" + i + "][" + j + "]: " + arr[i][j] + " "); } System.out.println(); } System.out.println("빙고는 총 " + isBingo + "개 입니다."); } }

개인적으로 java 배우면서 했던 실습문제중에 처음으로 ‘재밌다’ 고 느꼈던 문제였음!

물론 지금은 제발 이런것좀 코테에 나와주세요 하고 바라는중ㅠ

관련 게시물

Toplist

최신 우편물

태그