1-D arrays: store, index, and traverse · 1차원 배열: 저장, 인덱스, 순회
Many values in one box
- An array holds many values of the same type in order.
- Until now one variable held one value. An array holds a whole list.
- For example, the test scores of a class can live in one
intarray.
한 상자에 여러 값
- 배열은 순서대로 동일한 타입의 여러 값을 저장합니다.
- 지금까지는 하나의 변수가 하나의 값을 가졌습니다. 배열은 전체 목록을 저장합니다.
- 예를 들어, 학급의 시험 점수는 하나의
int배열에 담을 수 있습니다.
Make an array with values
- If you know the values, list them in curly braces
{ }. - The type is the element type plus
[], likeint[]. - Java counts how many values you gave and makes the array that size.
값이 포함된 배열 생성
- 값을 알고 있다면 중괄호
{ }안에 나열합니다. - 타입은 요소 타입 뒤에
[]를 붙인 것, 예로int[]입니다. - Java는 제공한 값의 개수를 세어 해당 크기의 배열을 만듭니다.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores[0]); // 90
System.out.println(scores[2]); // 70
}
}
Index positions
- Each value has an index (its position). Indexes start at 0.
- So the first value is
scores[0], the second isscores[1], and so on. - You can also change a value:
scores[1] = 85;.
인덱스 위치
- 각 값에는 인덱스(위치)가 있으며, 인덱스는 0부터 시작합니다.
- 따라서 첫 번째 값은
scores[0], 두 번째 값은scores[1], 이와 같이 계속됩니다. - 또한 값을 변경할 수도 있습니다:
scores[1] = 85;.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
scores[1] = 85; // change the middle value
System.out.println(scores[1]); // 85
}
}
Make an empty array
- Use
new int[n]to make an array ofnvalues. - Every
intslot starts at 0 automatically. - Then you fill the slots one by one.
빈 배열 생성
new int[n]를 사용하여n값들의 배열을 만듭니다.- 모든
int슬롯은 기본적으로 0으로 시작합니다. - 이후 슬롯을 하나씩 채웁니다.
public class Main {
public static void main(String[] args) {
int[] nums = new int[3]; // {0, 0, 0}
nums[0] = 5;
nums[1] = 6;
System.out.println(nums[0] + " " + nums[1] + " " + nums[2]); // 5 6 0
}
}
.length
array.lengthtells you how many values the array has.- Note: no parentheses — it is
scores.length, notscores.length(). - The last valid index is always
length - 1.
.length
array.length는 배열에 포함된 값의 개수를 알려줍니다.- 참고: 괄호가 없음 —
scores.length이며,scores.length()가 아닙니다. - 마지막 유효한 인덱스는 항상
length - 1입니다.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores.length); // 3
System.out.println(scores[scores.length - 1]); // 70 (last value)
}
}
Traverse with a for loop
- To visit every value, loop the index from
0up tolength - 1. - Use
i < array.lengthas the stop test. - Below we add up every value.
for 루프를 통한 순회
- 모든 값을 방문하려면 인덱스를
0부터length - 1까지 루프합니다. - 종료 조건으로
i < array.length를 사용합니다. - 아래에서는 모든 값을 더합니다.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int i = 0; i < scores.length; i++) {
total = total + scores[i];
}
System.out.println(total); // 240
}
}
Enhanced for loop
- The enhanced for (or "for-each") visits each value directly.
- Read it as: "for each
int vinscores". - Use it when you only need the values, not the index.
향상된 for 루프
- enhanced for(또는 "for-each")는 각 값을 직접 방문합니다.
- 이를 "for each
int vinscores"로 읽으십시오. - 인덱스가 아닌 값만 필요한 경우에 사용합니다.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int v : scores) {
total = total + v;
}
System.out.println(total); // 240
}
}
Common mistakes
a.lengthhas no(); valid indexes run0toa.length - 1.- Going out of range throws ArrayIndexOutOfBoundsException.
흔한 실수
a.length에는()가 없으며, 유효한 인덱스는0부터a.length - 1까지입니다.- 범위를 벗어날 경우 ArrayIndexOutOfBoundsException이 발생합니다.
Now you try
- Some tasks print a result; others complete a method the Harness calls.
- Remember: indexes start at 0, and the last index is
length - 1. - Press Run to compile, then Check answer.
이제 직접 해보기
- 일부 과제는 결과를 출력하고, 다른 과제는 Harness가 호출하는 메서드를 완성합니다.
- 기억하세요: 인덱스는 0부터 시작하며, 마지막 인덱스는
length - 1입니다. - 컴파일하려면 Run을 누르고, 그 후 Check answer를 누르십시오.
A 1-D array, indexed · 인덱싱된 1차원 배열
An array stores values in order; reach one with a[i]. · 배열은 값들을 순서대로 저장하며, **a[i]**로 특정 값을 접근할 수 있습니다.
The array nums is already filled. Use a loop to add up all its values and print the total on one line. For {4, 8, 15, 16, 23, 42} the output is 108. · 배열 nums는 이미 채워져 있습니다. 루프를 사용하여 모든 값을 합산하고 총합을 한 줄로 출력하세요. {4, 8, 15, 16, 23, 42}의 출력 결과는 108입니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete sum(int[] a) so it returns the sum of all values in the array. An empty array should return 0. The checker calls it with several arrays. · sum(int[] a)를 완성하여 배열 내 모든 값의 합을 반환하게 하세요. 빈 배열의 경우 0을 반환해야 합니다. 체크 프로그램은 여러 배열로 이를 테스트합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete doubleAll(int[] a). It does not return anything. Instead it changes the array in place so every value becomes twice as big. {1, 2, 3} becomes {2, 4, 6}. · doubleAll(int[] a)를 완성하세요. 아무것도 반환하지 않고, 배열 자체를 수정하여 모든 값을 두 배로 만듭니다. {1, 2, 3}는 {2, 4, 6}로 바뀝니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.