단순 for문
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
int[] arr = {10, 20, 30};
// for loop문 => 단순한 for문
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
for each문(향상된 for문 / 개선된 for문)
배열 또는 컬렉션과 함께 사용됨
배열 또는 컬렉션의 0번 인덱스부터 마지막 인덱스까지 순차적으로 모두 접근할 목적일 때
[표현법]
for(순차적으로 접근할 값을 담을 변수 선언: 순차적으로 접근할 배열 또는 컬렉션) { // 반복횟수 == 배열 또는 컬렉션의 크기
반복적으로 실행할 내용
}
Phone 클래스
package com.kh.chap02_objectArray.model.vo;
public class Phone {
// 이름, 브랜드명, 가격, 시리즈
private String name;
private String brand;
private int price;
private String series;
// 기본생성자
public Phone() {
}
// 매개변수 생성자
public Phone(String name, String brand, int price, String series) {
this.name = name;
this.brand = brand;
this.price = price;
this.series = series;
}
public void SetName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getBrand() {
return brand;
}
public void setPrice(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
public void setSeries(String series) {
this.series = series;
}
public String getSeries() {
return series;
}
public String information() {
return name + " " + brand + " " + price + " " + series;
}
}
향상된 for 문을 이용하여 배열을 출력하고 총합계와 평균값을 구하기
구매하고자 하는 핸드폰을 입력하고 그에 맞는 가격을 출력하기
package com.kh.chap02_objectArray.run;
import java.util.Scanner;
import com.kh.chap02_objectArray.model.vo.Phone;
public class ArrayForEach {
public static void main(String[] args) {
for(int value : arr) { // value = arr[0], value = arr[1], value = arr[2]
System.out.println(value);
}
// 객체배열
Phone[] phones = new Phone[3];
phones[0] = new Phone("갤럭시", "삼성", 1500000, "s23");
phones[1] = new Phone("아이폰", "애플", 1300000, "14pro");
phones[2] = new Phone("롤리팝", "엘지", 900000, "없음");
phones[2].setSeries("1");
int total = 0;
for(Phone p : phones) { // p = phones[0], p = phones[1], p = phones[2]
System.out.println(p.information());
// 모든인덱스의 금액 누적합 => total += i;
total += p.getPrice();
}
System.out.println("총합계 : " + total + "원");
System.out.println("평균가 : " + total / phones.length + "원");
// 구매하고자 하는 핸드폰
// 롤리팝
// 가격 : xx원 => 향상된 for문
Scanner sc = new Scanner(System.in);
System.out.print("구매하고자 하는 핸드폰 : ");
String str = sc.nextLine();
for(Phone p : phones) { // p = phones[0], p = phones[1], p = phones[2]
if(p.getName().equals(str)) { // 순차탐색
System.out.println("가격 : " + p.getPrice() + "원");
}
}
sc.close();
}
}
컴파일