JAVA Eclipse 12 배열 : 배열의 개념 및 사용
배열
: 같은 자료형을 가진 변수들의 나열된 묶음 (순서대로)
-> 같은 타입의 변수들의 관리를 편하게 하기 위해서
배열의 사용 방법
배열의 선언과 생성
1. 타입[ ] 배열명 ;
2. 배열명 = new 타입 [길이];
타입[ ] 배열명 = new 타입[길이];
-> 선언과 생성을 동시에 하는 초기화
배열의 길이와 인덱스
: 배열의 값을 다루기 위해 인덱스 사용
인덱스(index): 배열의 위치값
ex.
int[ ] ar = new int[3];
-> ar[0], ar[1], ar[2]
* 배열의 시작번호=0
ar[0] = 10;
ar[1] = 11;
ar[2] = 12;
-> 배열의 각 요소는 '배열명[인덱스]'로 변수처럼 사용 가능
배열의 초기화와 출력
배열 생성 시 배열의 값은 배열의 타입에 해당하는 기본값으로 초기화
정수형 배열의 초기값 : 0
문자형 배열의 초기값 : ' '
실수형 배열의 초기값 : 0.0
문자열 배열의 초기값 : Null
ex.
public class InitAr {
public static void main(String[] args) {
int arInt[] = new int[3];
double arDouble[] = new double[3];
char arChar[] = new char[3];
String arString[] = new String[3];
for (int i=0; i<3; i++) {
System.out.print(arInt[i] + " ");
}
System.out.println();
System.out.println("===============================");
for (int i=0; i<3; i++) {
System.out.print(arDouble[i] + " ");
}
System.out.println();
System.out.println("===============================");
for (int i=0; i<3; i++) {
System.out.print(arChar[i] + " ");
}
System.out.println();
System.out.println("===============================");
for (int i=0; i<3; i++) {
System.out.print(arString[i] + " ");
}
System.out.println();
System.out.println("===============================");
}
}
ex2.
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
int[] a = new int[] {10, 20, 4, 25, 18};
int [] b = {1, 2, 3, 4, 5, 6, 7};
// b라는 정수형 배열을 생성할 때, 초기값으로 넣는 방법으로 new int[ ] 는 생략 가능하다
int c[] = new int[10];
for (int i=0; i<c.length; i++) {
System.out.println(c[i]);
}
System.out.println(c);
System.out.println(Arrays.toString(c));
}
}
array는 문자형 정수값으로 변환해 주어야 한다.
ex3.
public class Array_2 {
public static void main(String[] args) {
int[] students = {100, 95, 90, 88, 93};
int sum = 0;
for(int i=0; i<students.length; i++) {
sum+=students[i];
}
System.out.println("시험 점수 평균 : " + sum/(float)students.length);
}
}
JAVA Eclipse 01 프로그램, 프로그래밍, 기계어, JAVA
https://developernew.tistory.com/63
JAVA Eclipse 02 자바 출력메서드와 입력메서드
https://developernew.tistory.com/71
JAVA Eclipse 03 변수, 자료형, 형변환, 변수의 상수화
https://developernew.tistory.com/74
JAVA Eclipse 04 연산자 정의, 연산자 종류, 연산자 우선순위
https://developernew.tistory.com/78
JAVA Eclipse 05 논리연산자, 비트연산자
https://developernew.tistory.com/80
JAVA Eclipse 06 기타연산자 - 삼항연산자, 대입연산자, 복합대입연산자, instanceof
https://developernew.tistory.com/84
JAVA Eclipse 07 제어문 : 조건문
https://developernew.tistory.com/88
JAVA Eclipse 08 제어문 : 조건문 switch + Random 클래스
https://developernew.tistory.com/93
JAVA Eclipse 09 제어문 : 반복문 for
https://developernew.tistory.com/102
JAVA Eclipse 10 제어문 : 반복문 while, do-while
https://developernew.tistory.com/103
JAVA Eclipse 11 제어문 : 반복문의 break, continue
https://developernew.tistory.com/106