백준-6
백준 실습
X보다 작은수


해당 문제는 최초로 몇번 굴릴건지 값을 받고
for문으로 arrylist의 굴릴 값많큼 넣는다
이후 그중에서 작은 숫자들만 출력하면된
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> num = new ArrayList<>();
int tun = sc.nextInt();
int x = sc.nextInt();
for(int i = 1; i <= tun; i++){
num.add(sc.nextInt());
}
for(int y = 1; y <= tun; y++){
int nums = num.get(y);
if(nums < x){
System.out.print(nums);
}
}
}
}
해당 코드로 시도해봤지만
423Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
오류가 나왔다
해당 오류는 인덱스 10에 접근하려했지만 데이터 구조의 크기가 10이기 떄문에 유효한 인덱스 범위는 “0~9”이기 때문이다
인덱스는 0부터 시작하기 때문에 10번쨰 요소에 접글할려면 인덱스 9를 사용해야한다
즉
int i = 0;
int y = 0;
0부터 시작하면 된다는 거다.
해결한 코드
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> num = new ArrayList<>();
int tun = sc.nextInt();
int x = sc.nextInt();
for(int i = 0; i < tun; i++){
num.add(sc.nextInt());
}
for(int y = 0; y < tun; y++){
int nums = num.get(y);
if(nums < x){
System.out.print(nums + " ");
}
}
}
}
댓글남기기