자바의 배열에서 가장 큰 문제는 배열은 길이를 바꿀 수 없다는 것이다. 그래서 배열의 길이를 늘리기 위해서는 길이가 긴 새로운 배열을 만들어 기존 배열을 복사해야 한다.
아래 예시는 명령을 받아서 "종료" 시 종료, "등록" 시 새로운 숫자를 하나씩 배열에 추가, "출력"시 배열을 출력하는 것이다.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] intArray = new int[0];
String cmd;
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.print("명령) ");
cmd = scanner.nextLine();
if(cmd.equals("종료")) {
break;
}else if(cmd.equals("등록")){
intArray = Arrays.copyOf(intArray,intArray.length+1); // 배열 길이 1증가
System.out.print("등록하기 원하는 숫자를 입력해주세요. : ");
intArray[intArray.length-1] = Integer.parseInt(scanner.nextLine());
}else if(cmd.equals("출력")){
System.out.println(Arrays.toString(intArray));
}
}
}
}
