본문 바로가기
자바(Java)/자바기초

[자바기초.028] for-each loop

by 긱펀 2024. 3. 29.
반응형

[자바기초.028] for-each loop

 

1.for-each 반복문(Enhanced for 반복문)

  • 배열에 사용하면 좋을 for each loop(enhanced for loop)이 있습니다.
  • for-each문은 그냥 일반적인 for문보다 사용하기 편합니다.
  • for문의 index나 [ ] 괄호를 사용하지 않고 반복문 순회(traverse)를 할 수 있는게 for-each 문입니다.

 

[예제1] 

아래 코드는 String형, int 형 배열을 for-each loop으로 순회하며 요소값을 출력하는 코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
    public static void main(String[] args) {
        int[] scores = { 85908878};
        String[] names = {"Tom""Jane""John""Sara"};
        // for each loop: for each value in highScores
        // for (type variable : arrayname)
        for (int value : scores)
        {
            // Notice no index or [ ], just the variable value!
            System.out.println( value );
        }
        // for each loop with a String array to print each name
        // the type for variable name is String!
        for (String name : names)
        {
            System.out.println(name);
        }
    }
}
cs
  • for-each loop를 사용하면 배열의 첫 번째 요소(element)부터 마지막 요소까지 하나씩 자동적으로 접근할 수 있다.
  • for-each loop를 사용하면 배열의 index를 사용하지 않아도 된다.
  • Java에서 for-each loop는 배열과 ArrayList에서 사용하면 된다.

 

[유제1-1]

int type의 배열이름 "number"를 만들고, 그 요소로 1,2,3,4,5를 저장하세요. 그리고 number 배열의 요소를 for-each loop으로 차례대로 하나씩 출력하세요.

 

[유제1-2]

아래 코드는 일반적인 for 반복문을 이용해, 배열의 요소 중 짝수(even number)만 출력하는 코드입니다. 이 코드를 enhanced-for loop으로 바꾸어 다시 코딩해 보세요.

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
    public static void main(String[] args) {
        int[] values = {5,10,7,12,19,14,21,24};
        // Rewrite this loop as a for each loop and run
        for (int i = 0; i < values.length; i++)
        {
            if (values[i] % 2 == 0)
            {
                System.out.println(values[i] + " is even!");
            }
        }
    }
}
cs

 

 

 

2.for-each loop의 한계

  • 일반 for 반복문으로 배열안의 요소들의 값을 변경하면, 실제로 배열의 요소값이 수정됩니다.
  • 하지만 for-each 반복문으로 배열의 요소들 값을 변경하면, 실제로 배열의 요소값이 수정되지 않는 한계가 있습니다.

 

[예제2]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main {
    public static void main(String[] args) {
        int[] values = {1,1,1};
        // Rewrite this loop as a for each loop and run
        for(int v : values) 
        {
            v = v + 2;
            System.out.print(v + " "); // 3 3 3
        }
        System.out.println("\nAfter the loop");
        for(int v: values) 
        {
            System.out.print(v + " "); // 1 1 1
        }
    }
}
cs

 

[중요]
Enhanced for each loop은 배열의 요소값을 변경하는 데에 사용할 수 없고, 오직 배열의 요소값을 순회(traverse)하는데에만 사용하세요. .

 

 

[유제2-1]

아래의 3가지 내용 중, for-each loop를 일반 for loop대신에 사용하는 이유로 알맞은 것은?


I: If you wish to access every element of an array.
II: If you wish to modify elements of the array.
III: If you wish to refer to elements through a variable name instead of an array index.

 

A. Only I.
B. I and III only.
C. II and III only.
D. All of the Above.

 

[유제2-2]

아래 코드의 실행 결과로 출력되는 값은?

1
2
3
4
5
6
7
8
9
int[ ] numbers = {44332211};
for (int num : numbers)
{
    num *= 2;
}
for (int num : numbers)
{
    System.out.print(num + " ");
}
cs

 

A. 44 33 22 11
B. 46 35 24 13
C. 88 66 44 22
D. The code will not compile.

 

 

3.Class 안에서 사용되는 배열과 for-each loop

아래 예제는 Class안에서 private instance로서 배열을 선언하여 사용하는 예시코드입니다. 그리고 이 배열을 for-each loop으로 순회하며 평균값을 리턴하는 메소드도 포함되어 있습니다.

 

[예제3]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ArrayWorker
{
    private int[] values;
 
    public ArrayWorker(int[] theValues)
    {
        values = theValues;
    }
 
    public double getAverage()
    {
        double total = 0;
        for (int val : values)
        {
            total = total + val;
        }
        return total / values.length;
    }
 
    public static void main(String[] args)
    {
        int[] numArray = {267125};
        ArrayWorker aWorker = new ArrayWorker(numArray);
        System.out.println(aWorker.getAverage()); // 6.4
    }
}
cs

 

 

[유제3-1] 

아래 코드는 배열의 최대값(Max)을 알려주는 ArrayMax 클래스와 그 예시코드 입니다.

이 클래스 안의 getMax()메소드는 일반 for 반복문으로 코딩되어 있습니다. 이것을 for-each 반복문으로 수정하여 코딩해 보세요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ArrayMax
{
    private int[] values;
    
    public ArrayMax(int[] array)
    {
        values = array;
    }
    public int getMax()
    {
        int max = values[0];
        for(int i = 1; i < values.length; i++)
        {
            if(values[i] > max)
            {
                max = values[i];
            }
        }
        return max;
    }
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        ArrayMax am = new ArrayMax(arr);
        System.out.println(am.getMax()); // 5
    }
}
cs

 

 

[유제3-2]

위의 ArrayMax 클래스 코드를 참고하여, 배열의 최소값을 알려주는 ArrayMin 클래스를 새롭게 하나 만들고, 유제3-1처럼 main 메소드에서 예시코드를 작성해 보세요.

1
2
3
4
public class ArrayMin
{
   /*********/
}
cs

 

 

[유제3-3] 

Given that array is an array of integers and target is an integer value, which of the following best describes the conditions under which the following code segment will return true?

1
2
3
4
5
6
boolean temp = false;
for (int val : array)
{
  temp = ( target == val );
}
return temp;
cs

 

 

[유제 정답은 아래 "더보기" 클릭]

더보기

[유제1-1 정답]

1
2
3
4
5
6
7
8
public class Main {
    public static void main(String[] args) {
        int[] number = {1,2,3,4,5};
        for(int value : number) {
            System.out.println(value);
        }
    }
}
cs

 

[유제1-2 정답]

public class Main { public static void main(String[] args) { int[] values = {5,10,7,12,19,14,21,24}; // Rewrite this loop as a for each loop and run for(int v : values) { if(v % 2 == 0) { System.out.println(v + " is even!"); } } } }

 

[유제2-1 정답]

 B

(For-each loops access all elements and enable users to use a variable name to refer to array elements, but do not allow users to modify elements directly.)

 

[유제2-2 정답]

 A

(The array is unchanged because the foreach loop cannot modify the array elements.)

 

[유제3-1 정답]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class ArrayMax
{
    private int[] values;
    
    public ArrayMax(int[] array)
    {
        values = array;
    }
    public int getMax()
    {
        /*
        int max = values[0];
        for(int i = 1; i < values.length; i++)
        {
            if(values[i] > max)
            {
                max = values[i];
            }
        }
        return max;
        */
        
        int max = values[0];
        for(int val : values)
        {
            if(val > max) max = val;
        }
        return max;
        
    }
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        ArrayMax am = new ArrayMax(arr);
        System.out.println(am.getMax());
    }
}
cs

 

 [유제3-2 정답]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class ArrayMin
{
    private int[] values;
    public ArrayMin(int[] array)
    {
        values = array;
    }
    public int getMin()
    {
        int min = values[0];
        for(int v : values)
        {
            if(v < min) min = v;
        }
        return min;
    }
    
    public static void main(String[] args)
    {
        int[] testArray = {1,2,3,4,5};
        ArrayMin am = new ArrayMin(testArray);
        System.out.println(am.getMin());
    }
}
cs

 

[유제3-3 정답]

C

(The variable temp is assigned to the result of checking if the current element in the array is equal to target. The last time through the loop it will check if the last element is equal to val.)

 


 

728x90
반응형

댓글