for문 for문
배열이나 나열의 크기만큼 루프를 돌며 각 원소를 순차적으로 접근하는 데 유용한 for문
for( 각 요소 값 : 배열이나 컨테이너 값 )
{
반복 수행할 작업
}
public class ForEach {
public static void main(String[] args) {
String[] numbers = {"one", "two", "three"};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
라는 코드가 있다. 이를 for-each문으로 바꾸면
public class ForEach {
public static void main(String[] args) {
String[] numbers = {"one", "two", "three"};
for (String number : numbers) {
System.out.println(number);
}
}
}
public class ForEach {
public static void main(String[] args) {
int[] n = {1, 2, 3, 4, 5};
int sum = 0;
for (int k : n) {
sum += k;
}
System.out.println(sum);
}
}
를 for문으로 바꾸면 다음과 같다.
public class ForEach {
public static void main(String[] args) {
int[] n = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < n.length; i++) {
int k = n[i];
sum += k;
}
System.out.println(sum);
}
}
public class ForEach {
public static void main(String[] args) {
int[] scores = {95, 71, 84, 93, 87};
int sum = 0;
for (int score : scores) {
sum += score;
}
System.out.println("점수 총합 = " + sum);
double avg = (double) sum / scores.length;
System.out.println("점수 평균 = " + avg);
}
}
문자열과 나열(enum)타입도 마찬가지.
public class ForEach {
enum Week {월, 화, 수, 목, 금, 토, 일}
public static void main(String[] args) {
int[] n = {1, 2, 3, 4, 5};
String names[] = {"사과", "배", "바나나", "체리", "딸기", "포도"};
int sum = 0;
for (int k : n) {
System.out.print(k + " ");
sum += k;
}
System.out.println(sum);
for (String s : names)
System.out.print(s + " ");
System.out.println();
for (Week day : Week.values())
System.out.print(day + "요일 ");
System.out.println();
}
}