JAVA) 반복문과 배열

김승연·2023년 4월 29일

JAVA

목록 보기
3/3

반복문

  • for문과 while문
    while문반복 횟수가 상황에 따라 다른 경우에 사용하는 반면, for문반복횟수가 명확할 때 좋다.
  • while문 예시
int n = 1;
while (n <= 10) {
  System.out.println(n);
  n++;
}
  • for문 예시
for (int i = 1; i <= 9; i++) {
  System.out.printf("3 x %d = %d\n", i, 3 * i);
}

Python과 같이 break, continue 사용이 가능하다.

배열

자바의 배열은 Python의 List와 다르게 같은 형의 데이터만 저장할 수 있다.

배열이란?

여러 값을 하나의 변수로 묶은 것.

int[] scores = { 65, 74, 23, 75, 68, 96, 88, 98, 54 };


// 1) 배열 값 읽기(read)
int[] scores = {99, 88, 77};
System.out.println(scores[0]); // 99
System.out.println(scores[1]); // 88
System.out.println(scores[2]); // 77
// 2) 배열 값 변경(write)
System.out.println(scores[0]); // 99
scores[0] = 0; // 0번 인덱스 값 변경
System.out.println(scores[0]); // 0

length 키워드로 배열의 길이 알 수 있음

String[] names = {"Kim", "Lee", "Park", "Choi", "Oh", "Jo"};
int[] mathScores = {82, 76, 100, 92, 68, 96};
for (int i = 0; i < names.length; i++) {
  System.out.printf("%s : %d\n", names[i], mathScores[i]);
}

출처: https://cloudstudying.kr/courses/10

0개의 댓글