배열에서의 초기화 방법은 다양합니다. 몇 가지 예를 들면:
// 길이가 5인 정수 배열을 0으로 초기화
int[] array1 = new int[5];
// 초기값을 가지는 배열
int[] array2 = {1, 2, 3, 4, 5};
// 길이가 3인 문자열 배열
String[] array3 = new String[3];
// 객체 배열 초기화
Box[] boxes = new Box[3];
boxes[0] = new Box(101, "Coffee");
boxes[1] = new Box(202, "Computer");
boxes[2] = new Box(303, "Apple");
main 함수에서 'String[] args' 사용 방법은 프로그램 실행 시 명령행 인수(커맨드 라인 인수)를 받아오는 매개변수입니다. 예를 들면:
public static void main(String[] args) {
// args 배열에는 프로그램 실행 시 전달된 명령행 인수가 저장됨
// 예: java MyClass arg1 arg2
// args[0]에는 "arg1", args[1]에는 "arg2"가 저장됨
for (String arg : args) {
System.out.println(arg);
}
}
Enhanced for 문(향상된 for 문 또는 for-each 문)은 배열 또는 컬렉션을 순회하는 간편한 방법입니다. 예를 들면:
int[] numbers = {1, 2, 3, 4, 5};
// Enhanced for 문
for (int number : numbers) {
System.out.println(number);
}
public class Box {
private int boxNum;
private String contents;
public Box(int boxNum, String contents) {
this.boxNum = boxNum;
this.contents = contents;
}
public int getBoxNum() {
return boxNum;
}
@Override
public String toString() {
return "Box{" +
"boxNum=" + boxNum +
", contents='" + contents + '\'' +
'}';
}
}
양의 정수 100개를 랜덤 생성하여, 배열에 저장하고, 배열에 있는 정수 중에서 3의 배수만 출력해 보자.
import java.util.Random;
public class Program {
public static void main(String[] args) {
// 양의 정수 100개를 랜덤 생성하여 배열에 저장
int[] numbers = new int[100];
Random random = new Random();
for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextInt(Integer.MAX_VALUE) + 1;
}
// 배열에 있는 정수 중에서 3의 배수만 출력
for (int number : numbers) {
if (number % 3 == 0) {
System.out.println(number);
}
}
}
}
해당 객체에 인덱스 순서대로 가로 세로 설정 -
이번에는 반드시 scanner 로 입력 받을것
해당 배열에 있는 Rectangle 의 총넓이의 합을 구하시오.
또한 아래의 함수도 만들것(static 으로 만들것)
import java.util.Scanner;
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int calculateArea() {
return width * height;
}
public static int calculateTotalArea(Rectangle[] rectangles) {
int totalArea = 0;
for (Rectangle rectangle : rectangles) {
totalArea += rectangle.calculateArea();
}
return totalArea;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Rectangle[] rectangles = new Rectangle[3];
for (int i = 0; i < rectangles.length; i++) {
System.out.println("가로를 입력하세요:");
int width = scanner.nextInt();
System.out.println("세로를 입력하세요:");
int height = scanner.nextInt();
rectangles[i] = new Rectangle(width, height);
}
int totalArea = calculateTotalArea(rectangles);
System.out.println("총 넓이의 합: " + totalArea);
}
}
4행 4열짜리 정수형 배열을 선언 및 할당하고
1) 1 ~ 16까지 값을 차례대로 저장하세요.
2) 저장된 값들을 차례대로 출력하세요.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
public class ArrayExample {
public static void main(String[] args) {
int[][] arr = new int[4][4];
int value = 1;
// 1) 1 ~ 16까지 값을 차례대로 저장
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = value++;
}
}
// 2) 저장된 값들을 차례대로 출력
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
int[][] arr = new int[3][3];
출력====================
(0, 0)(0, 1)(0, 2)
(1, 0)(1, 1)(1, 2)
(2, 0)(2, 1)(2, 2)
public class ArrayExample {
public static void main(String[] args) {
int[][] arr = new int[3][3];
// 출력
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print("(" + i + ", " + j + ")");
if (j < arr[i].length - 1) {
System.out.print(" ");
}
}
System.out.println();
}
}
}
int[][] arr = {
{11},
{22, 33},
{44, 55, 66}
};
arr --> [0] ----------> [11] [1] -----> [22] [33] [2] -> [44] [55] [66]