소개
이 튜토리얼에서는 Java 에서 고정 크기 배열을 생성하고 사용하는 데 필요한 핵심 기술을 살펴봅니다. 배열은 동일한 유형의 여러 요소를 단일 변수에 저장할 수 있게 해주는 기본적인 데이터 구조입니다. Java 배열을 마스터함으로써, 더 고급 주제의 기반이 되는 중요한 프로그래밍 기술을 습득하게 됩니다.
이 Lab 에서는 실습을 통해 배열을 선언, 초기화 및 조작하는 방법을 배우게 됩니다. 각 단계는 이전 단계를 기반으로 구축되어 Java 에서 배열 연산에 대한 포괄적인 이해를 제공합니다.
첫 번째 Java 배열 만들기
Java 의 배열은 동일한 유형의 여러 변수를 저장하는 객체입니다. 다른 일부 데이터 구조와 달리, 배열이 생성되면 크기를 변경할 수 없습니다. 이는 배열이 미리 결정된 수의 요소를 저장하는 데 특히 효율적임을 의미합니다.
배열 선언 및 초기화
배열은 다양한 방식으로 생성할 수 있습니다. 가장 일반적인 방법을 살펴보겠습니다.
간단한 정수 배열 만들기
먼저, 프로젝트 디렉토리에 새 Java 파일을 만들어 보겠습니다. WebIDE 에서 "File" 메뉴를 클릭하고 "New File"을 선택한 다음 이름을 ArrayDemo.java로 지정합니다.
다음 코드를 파일에 추가합니다.
public class ArrayDemo {
public static void main(String[] args) {
// Method 1: Declare and initialize an array separately
int[] numbers; // Array declaration
numbers = new int[5]; // Array initialization with size 5
// Default values are assigned (all zeros for int array)
System.out.println("Array elements after initialization:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
System.out.println("\nArray length: " + numbers.length);
}
}
Java 프로그램을 컴파일하고 실행하려면 WebIDE 에서 터미널을 열고 (아직 열려 있지 않은 경우) 다음 명령을 실행합니다.
javac ArrayDemo.java
java ArrayDemo
다음과 유사한 출력을 볼 수 있습니다.
Array elements after initialization:
numbers[0] = 0
numbers[1] = 0
numbers[2] = 0
numbers[3] = 0
numbers[4] = 0
Array length: 5
보시다시피 Java 는 정수 배열의 모든 요소를 자동으로 0 으로 초기화합니다.
값으로 배열 초기화
이제 ArrayDemo.java 파일을 수정하여 배열을 생성하는 또 다른 방법, 즉 특정 값으로 초기화하는 방법을 포함해 보겠습니다.
public class ArrayDemo {
public static void main(String[] args) {
// Method 1: Declare and initialize an array separately
int[] numbers; // Array declaration
numbers = new int[5]; // Array initialization with size 5
// Default values are assigned (all zeros for int array)
System.out.println("Array elements after initialization:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
System.out.println("\nArray length: " + numbers.length);
// Method 2: Initialize with specific values
int[] scores = {85, 90, 75, 88, 92};
System.out.println("\nScores array elements:");
for (int i = 0; i < scores.length; i++) {
System.out.println("scores[" + i + "] = " + scores[i]);
}
}
}
업데이트된 프로그램을 컴파일하고 실행합니다.
javac ArrayDemo.java
java ArrayDemo
이제 추가 출력을 볼 수 있습니다.
Array elements after initialization:
numbers[0] = 0
numbers[1] = 0
numbers[2] = 0
numbers[3] = 0
numbers[4] = 0
Array length: 5
Scores array elements:
scores[0] = 85
scores[1] = 90
scores[2] = 75
scores[3] = 88
scores[4] = 92
다른 유형의 배열 만들기
다른 데이터 유형의 배열을 시연하기 위해 ArrayTypes.java라는 새 파일을 만들어 보겠습니다. WebIDE 에서 새 파일을 만들고 다음 코드를 추가합니다.
public class ArrayTypes {
public static void main(String[] args) {
// String array
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
System.out.println("String array elements:");
for (int i = 0; i < names.length; i++) {
System.out.println("names[" + i + "] = " + names[i]);
}
// Double array with initialization
double[] prices = {19.99, 29.99, 15.50, 99.99};
System.out.println("\nDouble array elements:");
for (int i = 0; i < prices.length; i++) {
System.out.println("prices[" + i + "] = " + prices[i]);
}
// Boolean array
boolean[] flags = new boolean[3];
flags[0] = true;
System.out.println("\nBoolean array elements:");
for (int i = 0; i < flags.length; i++) {
System.out.println("flags[" + i + "] = " + flags[i]);
}
}
}
이 프로그램을 컴파일하고 실행합니다.
javac ArrayTypes.java
java ArrayTypes
다음 출력을 보게 됩니다.
String array elements:
names[0] = Alice
names[1] = Bob
names[2] = Charlie
Double array elements:
prices[0] = 19.99
prices[1] = 29.99
prices[2] = 15.5
prices[3] = 99.99
Boolean array elements:
flags[0] = true
flags[1] = false
flags[2] = false
다른 데이터 유형에는 서로 다른 기본값이 있습니다.
- 숫자 유형 (int, double 등) 은 기본적으로 0 입니다.
- 부울은 기본적으로 false 입니다.
- 참조 유형 (String, 객체) 은 기본적으로 null 입니다.
이 단계에서는 Java 에서 배열을 만드는 기본 사항을 보여주었습니다. 배열을 선언하고, 값의 유무에 관계없이 초기화하고, 다른 데이터 유형의 배열을 만드는 방법을 배웠습니다.
배열 요소 작업
이제 배열을 만드는 방법을 알았으니, 배열 요소로 작업하는 방법을 살펴보겠습니다. 여기에는 값 설정, 요소 액세스 및 배열 내용 수정이 포함됩니다.
배열 요소 액세스 및 수정
다음 코드를 사용하여 WebIDE 에 ArrayOperations.java라는 새 파일을 만듭니다.
public class ArrayOperations {
public static void main(String[] args) {
// Create an integer array
int[] numbers = new int[5];
// Assign values to array elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Display the original array
System.out.println("Original array elements:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
// Access specific elements
int firstElement = numbers[0];
int thirdElement = numbers[2];
System.out.println("\nAccessing specific elements:");
System.out.println("First element: " + firstElement);
System.out.println("Third element: " + thirdElement);
// Modify array elements
numbers[1] = 25; // Change second element
numbers[4] = 55; // Change last element
// Display the modified array
System.out.println("\nArray after modification:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
}
}
이 프로그램을 컴파일하고 실행합니다.
javac ArrayOperations.java
java ArrayOperations
다음 출력을 볼 수 있습니다.
Original array elements:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Accessing specific elements:
First element: 10
Third element: 30
Array after modification:
numbers[0] = 10
numbers[1] = 25
numbers[2] = 30
numbers[3] = 40
numbers[4] = 55
배열 경계 및 예외 처리
배열로 작업할 때는 배열 경계를 이해하는 것이 중요합니다. Java 배열은 고정된 크기를 가지며, 이러한 경계 외부의 요소에 액세스하려고 하면 예외가 발생합니다.
다음 코드를 사용하여 ArrayBoundaries.java라는 새 파일을 만듭니다.
public class ArrayBoundaries {
public static void main(String[] args) {
int[] numbers = new int[3]; // Array with 3 elements (indices 0, 1, 2)
// Set values within boundaries
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
System.out.println("Array elements within boundaries:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
// Demonstrating boundary checking with try-catch
System.out.println("\nAttempting to access elements outside boundaries:");
try {
// This is valid
System.out.println("Accessing numbers[2]: " + numbers[2]);
// This will cause an ArrayIndexOutOfBoundsException
System.out.println("Attempting to access numbers[3]: " + numbers[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("Cannot access an index outside the array bounds (0 to " + (numbers.length-1) + ")");
}
}
}
이 프로그램을 컴파일하고 실행합니다.
javac ArrayBoundaries.java
java ArrayBoundaries
다음과 같은 출력을 볼 수 있습니다.
Array elements within boundaries:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
Attempting to access elements outside boundaries:
Accessing numbers[2]: 30
Error: Index 3 out of bounds for length 3
Cannot access an index outside the array bounds (0 to 2)
이는 Java 가 배열에 대한 경계 검사를 수행함을 보여줍니다. numbers[3]에 액세스하려고 하면 배열에 인덱스 0, 1, 2 의 요소만 있으므로 예외가 발생합니다.
배열에서 값 계산 및 저장
값을 계산하여 배열에 저장하는 실용적인 예제를 만들어 보겠습니다. TemperatureConverter.java라는 파일을 만듭니다.
public class TemperatureConverter {
public static void main(String[] args) {
// Array to store Celsius temperatures
double[] celsiusTemps = {0, 10, 20, 30, 40};
// Array to store converted Fahrenheit temperatures
double[] fahrenheitTemps = new double[celsiusTemps.length];
// Convert each Celsius temperature to Fahrenheit
for (int i = 0; i < celsiusTemps.length; i++) {
// Formula: F = C * 9/5 + 32
fahrenheitTemps[i] = celsiusTemps[i] * 9/5 + 32;
}
// Display the conversion table
System.out.println("Temperature Conversion Table:");
System.out.println("---------------------------");
System.out.println("Celsius | Fahrenheit");
System.out.println("---------------------------");
for (int i = 0; i < celsiusTemps.length; i++) {
System.out.printf("%-10.1f | %-10.1f\n",
celsiusTemps[i],
fahrenheitTemps[i]);
}
}
}
이 프로그램을 컴파일하고 실행합니다.
javac TemperatureConverter.java
java TemperatureConverter
출력은 온도 변환 표가 됩니다.
Temperature Conversion Table:
---------------------------
Celsius | Fahrenheit
---------------------------
0.0 | 32.0
10.0 | 50.0
20.0 | 68.0
30.0 | 86.0
40.0 | 104.0
이 예제는 배열을 사용하여 관련 데이터를 저장하고 여러 값에 대해 효율적으로 계산을 수행하는 방법을 보여줍니다.
이 단계에서는 배열 요소에 액세스하고 수정하고, 배열 경계를 처리하고, 실용적인 계산에 배열을 사용하는 방법을 배웠습니다. 이러한 기술은 더 복잡한 배열 연산의 기반을 형성합니다.
고급 배열 연산
이제 배열의 기본 사항을 이해했으므로 배열 반복, 검색 및 메서드와 함께 배열 사용을 포함한 보다 정교한 연산을 살펴보겠습니다.
배열 반복 기술
Java 는 배열 요소를 반복하는 여러 가지 방법을 제공합니다. 다음 코드를 사용하여 ArrayIteration.java라는 새 파일을 만듭니다.
public class ArrayIteration {
public static void main(String[] args) {
// Create a sample array
String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};
System.out.println("Array Iteration Methods:");
// Method 1: Standard for loop
System.out.println("\n1. Using standard for loop:");
for (int i = 0; i < fruits.length; i++) {
System.out.println("fruits[" + i + "] = " + fruits[i]);
}
// Method 2: Enhanced for loop (foreach)
System.out.println("\n2. Using enhanced for loop (foreach):");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Method 3: While loop
System.out.println("\n3. Using while loop:");
int index = 0;
while (index < fruits.length) {
System.out.println("fruits[" + index + "] = " + fruits[index]);
index++;
}
}
}
이 프로그램을 컴파일하고 실행합니다.
javac ArrayIteration.java
java ArrayIteration
다음 출력을 볼 수 있습니다.
Array Iteration Methods:
1. Using standard for loop:
fruits[0] = Apple
fruits[1] = Banana
fruits[2] = Cherry
fruits[3] = Date
fruits[4] = Elderberry
2. Using enhanced for loop (foreach):
Apple
Banana
Cherry
Date
Elderberry
3. Using while loop:
fruits[0] = Apple
fruits[1] = Banana
fruits[2] = Cherry
fruits[3] = Date
fruits[4] = Elderberry
각 반복 방법에는 장점이 있습니다.
- 표준 for 루프: 배열 인덱스 및 요소에 대한 액세스를 제공합니다.
- 향상된 for 루프: 요소만 필요한 경우 더 깔끔한 구문입니다.
- While 루프: 반복 조건이 더 복잡할 때 유용합니다.
배열에서 요소 검색
배열에서 요소를 검색하는 프로그램을 만들어 보겠습니다. ArraySearch.java라는 파일을 만듭니다.
public class ArraySearch {
public static void main(String[] args) {
// Create an array of numbers
int[] numbers = {10, 25, 33, 47, 52, 68, 79};
// Values to search for
int[] searchValues = {33, 50, 79};
for (int valueToFind : searchValues) {
boolean found = false;
int position = -1;
// Search through the array
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == valueToFind) {
found = true;
position = i;
break; // Exit the loop once found
}
}
// Display result
if (found) {
System.out.println(valueToFind + " found at position " + position);
} else {
System.out.println(valueToFind + " not found in the array");
}
}
}
}
이 프로그램을 컴파일하고 실행합니다.
javac ArraySearch.java
java ArraySearch
다음과 같은 출력을 볼 수 있습니다.
33 found at position 2
50 not found in the array
79 found at position 6
이는 대상 값을 찾거나 배열이 소진될 때까지 각 요소를 확인하는 기본 선형 검색 알고리즘을 보여줍니다.
메서드에 배열 전달
배열은 다른 변수와 마찬가지로 메서드에 전달할 수 있습니다. ArrayMethods.java라는 파일을 만듭니다.
public class ArrayMethods {
public static void main(String[] args) {
// Create an array
int[] values = {5, 10, 15, 20, 25};
// Display the original array
System.out.println("Original array:");
displayArray(values);
// Calculate and display the sum
int sum = calculateSum(values);
System.out.println("\nSum of all elements: " + sum);
// Calculate and display the average
double average = calculateAverage(values);
System.out.println("Average of all elements: " + average);
// Double all values in the array
doubleValues(values);
// Display the modified array
System.out.println("\nArray after doubling all values:");
displayArray(values);
}
// Method to display an array
public static void displayArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// Method to calculate the sum of array elements
public static int calculateSum(int[] arr) {
int sum = 0;
for (int value : arr) {
sum += value;
}
return sum;
}
// Method to calculate the average of array elements
public static double calculateAverage(int[] arr) {
int sum = calculateSum(arr);
return (double) sum / arr.length;
}
// Method to double all values in the array
public static void doubleValues(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
}
}
}
이 프로그램을 컴파일하고 실행합니다.
javac ArrayMethods.java
java ArrayMethods
다음과 같은 출력을 볼 수 있습니다.
Original array:
5 10 15 20 25
Sum of all elements: 75
Average of all elements: 15.0
Array after doubling all values:
10 20 30 40 50
이 예제는 몇 가지 중요한 개념을 보여줍니다.
- 배열은 매개변수로 메서드에 전달될 수 있습니다.
- 메서드는 배열에서 계산된 값을 반환할 수 있습니다.
- 메서드 내에서 배열 요소에 대한 변경 사항은 메서드 외부에도 반영됩니다 (배열은 참조로 전달됨).
최대 및 최소값 찾기
배열에서 최대 및 최소값을 찾는 프로그램을 만들어 보겠습니다. ArrayMinMax.java라는 파일을 만듭니다.
public class ArrayMinMax {
public static void main(String[] args) {
// Create an array of numbers
int[] numbers = {42, 17, 88, 23, 56, 9, 71, 33};
// Find minimum and maximum values
int min = findMinimum(numbers);
int max = findMaximum(numbers);
// Display the array
System.out.print("Array values: ");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
// Display results
System.out.println("Minimum value: " + min);
System.out.println("Maximum value: " + max);
}
// Method to find the minimum value in an array
public static int findMinimum(int[] arr) {
// Start with the first element as the minimum
int min = arr[0];
// Compare with other elements
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
// Method to find the maximum value in an array
public static int findMaximum(int[] arr) {
// Start with the first element as the maximum
int max = arr[0];
// Compare with other elements
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
}
이 프로그램을 컴파일하고 실행합니다.
javac ArrayMinMax.java
java ArrayMinMax
다음과 같은 출력을 볼 수 있습니다.
Array values: 42 17 88 23 56 9 71 33
Minimum value: 9
Maximum value: 88
이 단계에서는 다양한 반복 기술, 요소 검색, 메서드에 배열 전달, 최소 및 최대값 찾기를 포함한 몇 가지 고급 배열 연산을 배웠습니다. 이러한 기술은 Java 프로그램에서 배열을 보다 효과적으로 사용하는 데 도움이 됩니다.
실용적인 배열 응용
이 마지막 단계에서는 완전한 예제를 통해 배열의 실용적인 응용을 살펴보겠습니다. 실제 프로그래밍 시나리오에서 배열을 사용하는 방법을 보여주는 간단한 성적 관리 시스템을 만들 것입니다.
학생 성적 추적기 만들기
학생 성적을 관리하는 프로그램을 만들어 보겠습니다. 이 프로그램은 다음을 수행합니다.
- 학생 이름과 성적 저장
- 평균 성적 계산
- 최고 및 최저 성적 찾기
- 평균 이상 점수를 받은 학생 수 결정
WebIDE 에 GradeTracker.java라는 새 파일을 만듭니다.
public class GradeTracker {
public static void main(String[] args) {
// Arrays to store student information
String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Emma",
"Frank", "Grace", "Hannah", "Ian", "Julia"};
int[] studentGrades = {85, 92, 78, 65, 88, 72, 95, 83, 79, 91};
// Display all student records
System.out.println("Student Grade Records:");
System.out.println("---------------------");
System.out.println("Name\t\tGrade");
System.out.println("---------------------");
for (int i = 0; i < studentNames.length; i++) {
// Add extra tab for short names to align columns
String tab = studentNames[i].length() <= 5 ? "\t\t" : "\t";
System.out.println(studentNames[i] + tab + studentGrades[i]);
}
// Calculate statistics
int sum = 0;
int highest = studentGrades[0];
int lowest = studentGrades[0];
String highestStudent = studentNames[0];
String lowestStudent = studentNames[0];
for (int i = 0; i < studentGrades.length; i++) {
// Add to sum for average calculation
sum += studentGrades[i];
// Check for highest grade
if (studentGrades[i] > highest) {
highest = studentGrades[i];
highestStudent = studentNames[i];
}
// Check for lowest grade
if (studentGrades[i] < lowest) {
lowest = studentGrades[i];
lowestStudent = studentNames[i];
}
}
// Calculate average
double average = (double) sum / studentGrades.length;
// Count students above average
int aboveAverageCount = 0;
for (int grade : studentGrades) {
if (grade > average) {
aboveAverageCount++;
}
}
// Display statistics
System.out.println("\nClass Statistics:");
System.out.println("----------------");
System.out.printf("Class Average: %.2f\n", average);
System.out.println("Highest Grade: " + highest + " (" + highestStudent + ")");
System.out.println("Lowest Grade: " + lowest + " (" + lowestStudent + ")");
System.out.println("Number of students above average: " + aboveAverageCount);
}
}
이 프로그램을 컴파일하고 실행합니다.
javac GradeTracker.java
java GradeTracker
다음과 같은 출력을 볼 수 있습니다.
Student Grade Records:
---------------------
Name Grade
---------------------
Alice 85
Bob 92
Charlie 78
David 65
Emma 88
Frank 72
Grace 95
Hannah 83
Ian 79
Julia 91
Class Statistics:
----------------
Class Average: 82.80
Highest Grade: 95 (Grace)
Lowest Grade: 65 (David)
Number of students above average: 5
이 프로그램은 배열을 사용하여 관련 데이터 (학생 이름 및 성적) 를 관리하고 해당 데이터에 대한 계산을 수행하는 방법을 보여줍니다.
성적 범주 추가
이제 성적 범주를 추가하여 성적 추적기를 개선해 보겠습니다. EnhancedGradeTracker.java라는 새 파일을 만듭니다.
public class EnhancedGradeTracker {
public static void main(String[] args) {
// Arrays to store student information
String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Emma",
"Frank", "Grace", "Hannah", "Ian", "Julia"};
int[] studentGrades = {85, 92, 78, 65, 88, 72, 95, 83, 79, 91};
// Create arrays to count grades in each category
int[] gradeCounts = new int[5]; // A, B, C, D, F
// Display all student records with grade categories
System.out.println("Student Grade Records:");
System.out.println("------------------------------");
System.out.println("Name\t\tScore\tGrade");
System.out.println("------------------------------");
for (int i = 0; i < studentNames.length; i++) {
// Calculate letter grade
char letterGrade = calculateGrade(studentGrades[i]);
// Count grades by category
switch (letterGrade) {
case 'A': gradeCounts[0]++; break;
case 'B': gradeCounts[1]++; break;
case 'C': gradeCounts[2]++; break;
case 'D': gradeCounts[3]++; break;
case 'F': gradeCounts[4]++; break;
}
// Add extra tab for short names to align columns
String tab = studentNames[i].length() <= 5 ? "\t\t" : "\t";
System.out.println(studentNames[i] + tab + studentGrades[i] + "\t" + letterGrade);
}
// Calculate statistics
double average = calculateAverage(studentGrades);
// Display statistics
System.out.println("\nClass Statistics:");
System.out.println("----------------");
System.out.printf("Class Average: %.2f\n", average);
// Display grade distribution
System.out.println("\nGrade Distribution:");
System.out.println("------------------");
System.out.println("A: " + displayStars(gradeCounts[0]));
System.out.println("B: " + displayStars(gradeCounts[1]));
System.out.println("C: " + displayStars(gradeCounts[2]));
System.out.println("D: " + displayStars(gradeCounts[3]));
System.out.println("F: " + displayStars(gradeCounts[4]));
}
// Method to calculate the letter grade from a numeric score
public static char calculateGrade(int score) {
if (score >= 90) {
return 'A';
} else if (score >= 80) {
return 'B';
} else if (score >= 70) {
return 'C';
} else if (score >= 60) {
return 'D';
} else {
return 'F';
}
}
// Method to calculate the average of an integer array
public static double calculateAverage(int[] arr) {
int sum = 0;
for (int value : arr) {
sum += value;
}
return (double) sum / arr.length;
}
// Method to create a string of stars representing a count
public static String displayStars(int count) {
StringBuilder stars = new StringBuilder();
for (int i = 0; i < count; i++) {
stars.append("*");
}
return stars.toString() + " (" + count + ")";
}
}
이 프로그램을 컴파일하고 실행합니다.
javac EnhancedGradeTracker.java
java EnhancedGradeTracker
다음과 같은 출력을 볼 수 있습니다.
Student Grade Records:
------------------------------
Name Score Grade
------------------------------
Alice 85 B
Bob 92 A
Charlie 78 C
David 65 D
Emma 88 B
Frank 72 C
Grace 95 A
Hannah 83 B
Ian 79 C
Julia 91 A
Class Statistics:
----------------
Class Average: 82.80
Grade Distribution:
------------------
A: *** (3)
B: *** (3)
C: *** (3)
D: * (1)
F: (0)
이 향상된 예제는 다음을 보여줍니다.
- 관련 데이터를 저장하기 위해 여러 배열 사용
- 계산 및 서식을 위한 유틸리티 메서드 만들기
- 데이터 계산 및 분류
- 배열 데이터의 시각적 표현 생성
조건에 따라 배열 데이터 처리
마지막 예제로, 조건에 따라 배열 데이터를 처리하는 프로그램을 만들어 보겠습니다. FilteredGrades.java라는 파일을 만듭니다.
public class FilteredGrades {
public static void main(String[] args) {
// Arrays to store student information
String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Emma",
"Frank", "Grace", "Hannah", "Ian", "Julia"};
int[] studentGrades = {85, 92, 78, 65, 88, 72, 95, 83, 79, 91};
// Create a threshold for passing
int passingGrade = 75;
// Display all student records with pass/fail status
System.out.println("Student Grade Records:");
System.out.println("------------------------------");
System.out.println("Name\t\tScore\tStatus");
System.out.println("------------------------------");
// Count passing and failing students
int passingCount = 0;
for (int i = 0; i < studentNames.length; i++) {
String status = (studentGrades[i] >= passingGrade) ? "PASS" : "FAIL";
// Count passing students
if (studentGrades[i] >= passingGrade) {
passingCount++;
}
// Add extra tab for short names to align columns
String tab = studentNames[i].length() <= 5 ? "\t\t" : "\t";
System.out.println(studentNames[i] + tab + studentGrades[i] + "\t" + status);
}
// Create arrays to store only passing students
String[] passingStudents = new String[passingCount];
int[] passingScores = new int[passingCount];
// Fill the passing student arrays
int index = 0;
for (int i = 0; i < studentNames.length; i++) {
if (studentGrades[i] >= passingGrade) {
passingStudents[index] = studentNames[i];
passingScores[index] = studentGrades[i];
index++;
}
}
// Display only passing students
System.out.println("\nPassing Students (Score >= 75):");
System.out.println("------------------------------");
System.out.println("Name\t\tScore");
System.out.println("------------------------------");
for (int i = 0; i < passingStudents.length; i++) {
// Add extra tab for short names to align columns
String tab = passingStudents[i].length() <= 5 ? "\t\t" : "\t";
System.out.println(passingStudents[i] + tab + passingScores[i]);
}
// Calculate and display statistics
System.out.println("\nClass Statistics:");
System.out.println("----------------");
System.out.println("Total Students: " + studentNames.length);
System.out.println("Passing: " + passingCount);
System.out.println("Failing: " + (studentNames.length - passingCount));
System.out.printf("Pass Rate: %.1f%%\n",
(double) passingCount / studentNames.length * 100);
}
}
이 프로그램을 컴파일하고 실행합니다.
javac FilteredGrades.java
java FilteredGrades
다음과 같은 출력을 볼 수 있습니다.
Student Grade Records:
------------------------------
Name Score Status
------------------------------
Alice 85 PASS
Bob 92 PASS
Charlie 78 PASS
David 65 FAIL
Emma 88 PASS
Frank 72 FAIL
Grace 95 PASS
Hannah 83 PASS
Ian 79 PASS
Julia 91 PASS
Passing Students (Score >= 75):
------------------------------
Name Score
------------------------------
Alice 85
Bob 92
Charlie 78
Emma 88
Grace 95
Hannah 83
Ian 79
Julia 91
Class Statistics:
----------------
Total Students: 10
Passing: 8
Failing: 2
Pass Rate: 80.0%
이 예제는 다음을 보여줍니다.
- 배열과 함께 조건부 로직 사용
- 조건을 기반으로 필터링된 배열 생성
- 배열 데이터에서 통계 계산
- 정보를 형식화된 방식으로 표시
이 단계에서는 실용적인 문제를 해결하기 위해 배열을 적용하는 방법을 보았습니다. 관련 데이터를 관리하고, 계산을 수행하고, 조건을 기반으로 배열 데이터의 필터링된 보기를 만드는 방법을 배웠습니다. 이러한 기술은 실제 Java 애플리케이션에서 배열을 사용하는 강력한 기반이 될 것입니다.
요약
이 랩에서는 Java 에서 고정 크기 배열을 생성하고 사용하는 데 필요한 기술을 탐구했습니다. 다음 방법을 배웠습니다.
- 다양한 데이터 유형의 배열을 선언하고 초기화합니다.
- 배열 경계를 준수하면서 배열 요소에 액세스하고 수정합니다.
- 다양한 루핑 기술을 사용하여 배열을 반복합니다.
- 배열을 메서드에 전달하고 배열 데이터를 처리합니다.
- 배열에서 최소 및 최대값을 찾습니다.
- 성적 추적과 같은 실용적인 문제에 배열을 적용합니다.
배열은 Java 에서 많은 데이터 구조의 기초를 형성하며 효율적인 데이터 저장 및 조작에 필수적입니다. 이 랩에서 개발한 기술은 동적 데이터 구조, 알고리즘 및 객체 지향 프로그래밍과 같은 보다 고급 프로그래밍 개념의 구성 요소 역할을 합니다.
제공된 예제를 수정하고, 자체 배열 기반 애플리케이션을 만들고, java.util.Arrays 클래스에서 추가 배열 유틸리티에 대한 Java 문서를 탐색하여 배열을 계속 연습하십시오.



