JAVA
4. Java 배열(Array) 다루기
oioioa
2024. 12. 9. 15:00
자바의 가장 기본적인 데이터를 여러개 저장하는 데이터 스트럭처는 Array 다.
Array는 현업에서는 잘 사용하지 않는다.
현업에서는 ?
ArrayList , HashMap 를 주로 사용한다.
array(배열) 처리 방법
// array (배열)로 처리한다. => 여러 데이터를 변수 1개로 처리한다.
// 몇개의 데이터를 저장할지, 데이터의 갯수를 설정해야 한다.
// 1. 비어있는 공간을 만든다.(new int[3] 예)3개의 정수 공간을 만든다.)
int[] mathScore = new int[3];
// 데이터를 넣는다.(프로그램 언어는 0부터 시작)
mathScore[0] = 70;
mathScore[1] = 90;
mathScore[2] = 77;
array(배열) 가져오는 방법
// 배열에 저장된 데이터를 가져오는 방법!
// 배열의 첫번째 데이터 가져오기
System.out.println(mathScore[0]);
// 총점을 구하기 위해서는 저장된 데이터를 다 더해야 한다.
int totalScore = mathScore[0]+mathScore[1]+mathScore[2];
System.out.println(totalScore);
// 평균을 구하시오.
double avgScor = totalScore / 3.0;
System.out.println(avgScor);
array 반복하는 for 문을 사용할때 data.length 는 data 전체 배열 길이만큼 데이터를 가져온다.
double[] data = new double[5];
data[0] = 10.0;
data[1] = 20.0;
data[2] = 30.0;
for(int i = 0; i< data.length; i++){
System.out.println(data[i]);
}
array(배열) ex.
// 학생 10명의 점수가 있습니다.
// 70,77,100,97,43,66,88,69,58,91
// 1. 배열을 만드세요.(2번째 방법)
// 2. 데이터를 저장하세요.
int[] engScore = {70,77,100,97,43,66,88,69,58,91};
System.out.println(engScore[2]);
// 3. 총합을 구하세요.
int totalEngScore = 0;
for (int i = 0; i < 10; i++) {
totalEngScore = totalEngScore + engScore[i];
}
{
System.out.println(totalEngScore);
}
// 4. 평균을 구하세요.
System.out.println((totalEngScore)/10.0);
System.out.println(totalScore / (double)engScore.length);