20210729) 배열 - 반복문과 배열

0

JAVA

목록 보기
30/71

LoopArray
for문을 사용해 배열의 모든 요소를 출력하라
package application;

public class LoopArray {

public static void main(String[] args) {
	// for 반복문과 문자열의 인덱스를 이용해 문자열의 첫번째부터 끝까지 출력하라 
	String[] animals = {"개", "고양이", "닭"};
	for(int i=0 ; i<3 ; i++) {
	System.out.println(animals[i]);
	}
    /* 반복문으로 대체
    System.out.println(animals[0]);
    System.out.println(animals[1]);
    System.out.println(animals[2]);
    */

}

}

배열의 요소를 추가 "사자","양","말"
자동으로 그 길이(length)만큼 반복
인덱스 번호도 같이 출력

인덱스 0 : 개
인덱스 1 : 고양이
인덱스 2 : 닭
인덱스 3 : 사자
인덱스 4 : 양
인덱스 5 :

package application;

public class LoopArray {

public static void main(String[] args) {
	
	String[] animals = {"개", "고양이", "닭", "사자", "양", "말"};
	int[] numbers = {1, 2, 3, 4, 5}	;
	/*반복문으로 animals배열 요소들을 하나씩 출력
	for(int i=0 ; i<3 ; i++) {
		System.out.println(animals[i]);
	}
	*/
	// 반복문으로 animals 배열 요소들이 변화를 반영해서 출력
	for(int i=0 ; i<animals.length ; i++) {
		System.out.println("인덱스 " + i + " : " + animals[i]);
		//System.out.printf("인덱스 %d : %s\n", i, animals[i]);
	}
	//배열의 길이 (length) = 요소(아이템) 갯수
	System.out.println("animals 배열 길이는: " + animals.length);
}

}

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN