// 태어난 해를 받아 띠를 반환public class Zodiac { public static void main(String[] args) { int yearOfBirth = 1990; String[] zodiac = {"원숭이","닭","개","돼지","쥐", "소","호랑이","토끼","용","뱀","말","양"}; System.out.println(zodiac[yearOfBirth%12]); }}
split
java.lang 패키지 String 클래스 method
문자열 중 특정 문자열로 구분하여 문자열의 배열로 반환하는 메소드
구분된 문자열은 버림
csv(comma separated variables) 데이터를 구분할 때 많이 사용
.은 자를 수 없다.
한번에 하나의 문자를 구분해서 자름
여러개를 자를 수 없다.
java.util 패키지 StringTokenizer클래스를 사용하면 가능
public class SplitEx { public static void main(String[] args) { String data = "이재찬,이재현,정택성~공선의~김건하.최지우,노진경,김정운.김정윤"; String[] splitedData = data.split(","); // '[.]'같이 사용하면 '.'도 자를 수 있긴 함 // String[] splitedData = data.split("[.]"); System.out.println("구분된 배열 방의 갯수 : " + splitedData.length); for(String name : splitedData) { System.out.println(name); } }}
2차원 배열
행과 열로 구성된 배열
모든 행의 열의 개수는 같다
// 2차원 배열 - 참조형 형식// 1. 선언데이터형[][] 배열명 = null;// 2. 생성배열명 = new 데이터형[행의수][열의수];// 선언과 생성 동시에데이터형[][] 배열명 = new 데이터형[행의수][열의수];// 3. 값 할당배열명[행인덱스][열인덱스] = 값;// 4. 값 사용배열명[행인덱스][열인덱스]for(int i=0; i<배열명.length; i++) { // 행 for(int j=0; j<배열명[i].length; j++) { 배열명[i][j] }}// 2차원 배열의 한 행은 1차원 배열로 이루어져 있다.// 향상된 for 사용for(데이터형[] 1차원배열명 : 2차원배열명) { for(데이터형 변수명 : 1차원배열명) { 변수명 // 1차원 배열의 요소 값을 사용가능 }}// 2차원 배열 - 기본형 형식// '{}'를 행구분 괄호라고 함// = 뒤에 new 데이터형[][] 생략된 형태데이터형[][] 배열명 = { { 1행값,..}, { 2행값,.. }, {}, {}.. };// 행의 수배열명.length// 열의 수배열명[행번호].length
// 배열 선언 시 '[]'의 위치는 다음과 같이 줄 수 있다.데이터형[] 배열명 = null;데이터형 배열명[] = null; // 비추데이터형[][] 배열명 = null;데이터형 배열명[][] = null; // 비추// 데이터형뒤에 []를 붙이는게 더 좋음// int i[],j; // int i,j[][], k;// 변수명 뒤에 붙이면 개발자가 배열이 아니라고 혼동할 수 있음
// 2차원 배열 예public class Use2DArray { public Use2DArray() { // int[][] twoDArr = new int[2][3]; // 참조형 2차원 배열 생성하면 자동 초기화됨 int[][] twoDArr = { { 1, 2, 3 }, { 4, 5, 6 } }; // 기존 for문 for(int i=0; i<twoDArr.length; i++) { for(int j=0; j<twoDArr[i].length; j++) { System.out.printf(twoDArr[i][j]+" "); } System.out.println(); } // 향상된 for문 // 2차원 배열의 한행은 일차원 배열 for(int[] oneDArr : twoDArr) { for(int val : oneDArr) { System.out.print(val+" "); } System.out.println(); } } public static void main(String[] args) { new Use2DArray(); }}
// 학생의 Oracle, Java, JDBC 과목 점수를 처리하는 프로그램public class ScoreProcess2 { private int total; public void addScore(int score) { total += score; } public int getTotal() { return total; } public void resetTotal() { total = 0; } public String[] nameData() { String[] name = {"김정운","이재현", "정택성","노진경","최지우","김건하"}; return name; } public int[][] scoreData() { int[][] score = { {85, 86, 81}, {95, 91, 100}, {89, 71, 59}, {97, 96, 91}, {78, 74, 77}, {100, 95, 68}, }; return score; } public void printScore(String[] name, int[][] score) { System.out.println("번호\t이름\tOracle\tJava\tJDBC\t총점\t평균"); System.out.println("-----------------------------------------------------"); for(int i=0; i<name.length; i++) { System.out.printf("%4d\t%s\t",i+1,name[i]); for(int j=0; j<score[i].length; j++) { System.out.printf("%4d\t",score[i][j]); addScore(score[i][j]); } System.out.printf("%4d\t%.2f\t\n",getTotal(),(float)getTotal()/3); resetTotal(); } } public static void main(String[] args) { ScoreProcess2 sp2 = new ScoreProcess2(); // 처리할 데이터 받기 String[] name = sp2.nameData(); int[][] score = sp2.scoreData(); // 처리 sp2.printScore(name, score); }}
가변 배열(Variable Array)
행과 열로 구성된 배열 (2차원 배열 기반)
행마다 열의 개수가 다른 배열
// 행,열의 수를 구하는 건 2차원 배열과 동일// 행의 수배열명.length// 열의 수배열명[행의번호].length
// 1.선언)데이터형[][] 배열명 = null;// 2.생성) 행의 개수만 설정// 열의 개수를 설정하지 않는다! 배열명 = new 데이터형[행의개수][];// 3.행마다 열을 생성)배열명[행의번호] = new 데이터형[열의개수];// 이렇게 초기화 할 때 "new 데이터형[]"은 생략할 수 없다.배열명[행의번호] = new 데이터형[] { 값,값, ... };// 열의개수를 준 상태로 초기화 안됨!// new 데이터형[3] {1,2,3}; // error!// 4.값할당, 값사용 - 2차원 배열과 동일배열명[행번호][열번호] = 값;someVal = 배열명[행번호][열번호];// 모든방의 값 출력(일괄처리)for(int i=0; i<배열명.length; i++) { for(int j=0; j<배열명[i].length; j++) { System.out.printf("%4d", 배열명[i][j]); }}
// 행마다 열의 개수가 다른 가변 배열public class VariableArray { public VariableArray() { // 1.선언) 데이터형[][] 배열명 = null; int[][] arr = null; // 2.생성) 행의 개수만 설정. 배열명==new 데이터형[행의수][]; arr=new int[4][]; // 3.행마다 열생성) 배열명[행번호] = new 데이터형[열의개수]; arr[0] = new int[3]; arr[1] = new int[4]; arr[2] = new int[1]; // 초기화를 하려면 열의 개수는 설정하지 않는다. arr[3] = new int[] {1, 2, 3, 4, 5, 6}; // 4.값할당 arr[0][2] = 10; arr[1][3] = 20; arr[2][0] = 30; // 5. 값사용 System.out.println(arr[0][0]+" / "+arr[0][1]+" / "+arr[0][2]); // 모든 방의 값 출력 : 일괄처리 System.out.println("모든 결과 출력 "); for(int i=0; i<arr.length ; i++) { // 행 for(int j=0; j<arr[i].length; j++) { // 열 System.out.printf("arr[%d][%d]=%-5d", i,j,arr[i][j]); } System.out.println(); } } public static void main(String[] args) { new VariableArray(); }}
기본형 형식 사용
행구분 괄호로 묶여지는 값의 개수를 다르게 설정
데이터형[] 배열명 = { {값, 값.. }, {값}, {값, .. }, ...};
// 가변 배열의 기본형 형식 사용public class VariableArray2 { public void priType() { // 문법) 데이터형[][] 배열명 = { {값,.}, {..}, ... }; // 행구분 괄호로 묶여지는 값의 개수를 다르게 설정 String[][] arr = { {"딸기"}, {"포도","수박", "복숭아"}, {"사과","배", "감"}, {"뀰"} }; String[] title = { "봄","여름","가을","겨울" }; for(int i=0; i<arr.length; i++) { System.out.print(title[i]+" : "); for(int j=0; j<arr[i].length; j++) { System.out.print(arr[i][j]+"\t"); } System.out.println(); } } public static void main(String[] args) { new VariableArray2().priType(); }}