Java 정리 12
28 Nov 2018
Reading time ~6 minutes
Java 정리 12 - Array
최소값, 최대값 구하기
-
처음 방의 값을 변수에 저장하고 옆방의 값과 비교하여 변수 값이 작다면 옆 방의 값으로 변수의 값을 변경하고 변경된 변수의 값으로 그 다음 방의 값을 비교하여 변경하는 작업을 끝까지 수행한다.
- 반대로 구하면 최대값
// 학생들의 성적의 최소값, 최대값 구하기
public class ScoreProcess {
public ScoreProcess() {
String[] nameArr = { "이재찬","정택성","이재현","김건하","공선의" };
int[] scoreArr = { 89,76,99,64,50 };
int totalScore = 0; // 총점을 누적합
// 최대값 최소값을 저장할 변수, 첫 인덱스값으로 초기화
int highestScore = scoreArr[0];
int lowestScore = scoreArr[0];
System.out.println("번호\t이름\t점수");
System.out.println("-------------------------");
for(int i=0; i<nameArr.length; i++) {
System.out.printf("%d\t%s\t%d\n", i+1, nameArr[i], scoreArr[i]);
totalScore += scoreArr[i];
if (scoreArr[i] > highestScore)
highestScore = scoreArr[i];
if (scoreArr[i] < lowestScore) {
lowestScore = scoreArr[i];
}
}
System.out.println("-------------------------");
System.out.println("응시인원 : "+nameArr.length+"명");
System.out.printf("총점[%-5d] 평균[%.2f]\n", totalScore,
totalScore/(float)nameArr.length);
// casting안하면 결과는 정수가 나옴
System.out.println("정수 평균값 : " + totalScore/nameArr.length);
System.out.printf("최고점[%d] 최저점[%d]\n", highestScore, lowestScore);
}
public static void main(String[] args) {
new ScoreProcess();
}
}
정렬
- 내림차순 선택정렬
- 처음방의 값과 옆방의 값을 비교하여 처음방의 값이 뒷방의 값보다 작다면 앞방의 값과 뒷방의 값을 바꾼다. 이 작업이 끝방까지 된 후 두번째 방부터 옆방을 비교하여
- 반대로 구하면 오름차순
// 학생들의 성적을 정렬 후 출력
public class ScoreProcess {
public ScoreProcess() {
String[] nameArr = { "이재찬","정택성","이재현","김건하","공선의" };
int[] scoreArr = { 89,76,99,64,50 };
System.out.println("번호\t이름\t점수");
System.out.println("-------------------------");
for(int i=0; i<nameArr.length; i++) {
System.out.printf("%d\t%s\t%d\n", i+1, nameArr[i], scoreArr[i]);
}
// 선택정렬
int temp;
String tmpStr;
for(int i=0; i<scoreArr.length-1; i++) {
for(int j=i+1; j<scoreArr.length; j++) {
if (scoreArr[i] > scoreArr[j]) {
temp = scoreArr[i];
scoreArr[i] = scoreArr[j];
scoreArr[j] = temp;
tmpStr = nameArr[i];
nameArr[i] = nameArr[j];
nameArr[j] = tmpStr;
}
}
}
System.out.println("-------------------------");
System.out.println("선택 정렬 후 ");
System.out.println("-------------------------");
for(int i=0; i<nameArr.length; i++) {
System.out.printf("%d\t%s\t%d\n", i+1, nameArr[i], scoreArr[i]);
totalScore += scoreArr[i];
}
}
public static void main(String[] args) {
new ScoreProcess();
}
}
배열을 이용하여 띠구하기
- 배열을 이용하면 if나 switch로 구현하는 긴 코드를 아래처럼 줄일 수 있다.
// 태어난 해를 받아 띠를 반환
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();
}
}