동적배열: 원소의 개수에 따라 자동으로 크기가 변하는 배열
ArrayList<참조타입> 참조변수 = new ArrayList<>();
<참조타입>:기초타입의 동적배열이라면 lnteger,long,short,float,double,charter,boolean을 사용한다.
참조변수.add:데이터를 동적배열에 원소로 추가
참조변수.remove:인덱스 번호의 원소를 제거
참조변수.get:인덱스번호의 원소를 가져오기
동적배열에 포함된 원소의 갯수
동적배열을 선언하고 7개의 값을 받아들이고 평균값과 함께 전부 출력한다.
세번째 원소를 제거하고 평균값과 함께 출력한다.
package 문자열배열열거타입;
import java.util.ArrayList;
import java.util.Scanner;
public class 동적배열문제1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> scores = new ArrayList<>();
int data;
int sum = 0;
while ((data = in.nextInt()) >= 0) // 키보드에서 입력된 값이 음수가 아닐때까지 반복한다.
scores.add(data); // 데이터를 동적배열에 추가한다.
System.out.println("입력건수=" + scores.size());
for (int i = 0; i < scores.size(); i++) {
sum += scores.get(i);
System.out.printf("원소%d=%d", i + 1, scores.get(i));
}
System.out.println("입력건수=" + scores.size());
System.out.println("평균=" + (double) sum / scores.size());
scores.remove(2);
System.out.println("입력건수=" + scores.size());
sum = 0;
for (int i = 0; i < scores.size(); i++) {
sum += scores.get(i);
System.out.printf("원소%d=%d", i + 1, scores.get(i));
}
System.err.println("");
System.out.println("평균=" + (double) sum / scores.size());
}
}
*sum값을 재정의 하지않고 하는법
sum -= scores.get(2);// 기존sum에서 두번째값을 제거
scores.remove(2);// 2번째값제거
System.out.println("입력건수=" + scores.size());
for (int i = 0; i < scores.size(); i++) {
System.out.printf("원소%d=%d", i + 1, scores.get(i));
}
System.err.println("");
System.out.println("평균=" + (double) sum / scores.size());
-반복실행을 위해 증감식을 사용하지 않는다.!
public class 배열반복문연습 {
public static void main(String[] args) {
double[] one2five = { 0.5, 1.5, 2.5, 3.5, 4.5, 5.5 };//배열 선언 정의
double sum = 0;
for (int a = 0; a < one2five.length; a++) {
one2five[a]++; // 배열안에 있는값 1씩 추가
->one2five={1.5,2.5,3.5,4.5,5.5,6.};
System.out.printf("x[%d]=%.1f", a, one2five[a]);
}
//for-each문
for (double a : one2five) {
System.out.printf("x[%.1f]=%.1f", a, a);
sum += a;
}
System.out.println("");
System.out.println("평균:" + sum / one2five.length);
for (double a : one2five) {
System.out.printf("x[%d]=%.1f", (int) a, a);
}
System.out.printf("\n평균:%.1f", sum / one2five.length);
System.out.printf("one2fivelength: %d ", one2five.length);
}
}
class Hexa {
double sideA;
double sideB;
double height;
public Hexa(double a, double b, double h) {
this.sideA = a;
this.sideB = b;
this.height = h;
}
double findArea() {
return sideA * sideB * height;
}
}
public class 객체배열연습 {
public static void main(String[] args) {
Hexa[] hexa = new Hexa[4];
for (int i = 0; i < hexa.length; i++) {
hexa[i] = new Hexa(i + 3.0, i + 4.0, i + 6.0);
System.out.printf("한변의길이:%.1f 다른변의길이:%.1f 높이: %.1f ==%.1f\n", hexa[i].sideA, hexa[i].sideB,
hexa[i].height, hexa[i].findArea());
}
}
한변의길이:3.0 다른변의길이:4.0 높이: 6.0 ==72.0
한변의길이:4.0 다른변의길이:5.0 높이: 7.0 ==140.0
한변의길이:5.0 다른변의길이:6.0 높이: 8.0 ==240.0
한변의길이:6.0 다른변의길이:7.0 높이: 9.0 ==378.0