국비교육 10일차 Java : 랜덤으로 숫자 뽑기, 배열
랜덤한 정수 = (int) (Math.random()*구간범위) + 시작값;
System.out.println("1부터 10까지 랜덤으로 정수 뽑기 => " + ( (int) (Math.random()*(10-1+1)) + 1) );
Random rnd = new Random();
// 객체 생성 Random rnd 후 rnd.nextInt(마지막수-처음수+1) + 처음수;
System.out.println("1부터 10까지 랜덤으로 정수 뽑기 => " + ( rnd.nextInt(10-1+1) + 1) );
public static void main(String[] args) {
Random rnd = new Random();
String authentication_key = "";
for(int i=0; i<3; i++) {
authentication_key += rnd.nextInt(9-0+1) + 0;
// 랜덤한 숫자를 authentication_key에다가 차곡 차곡 쌓아주는 역할
}
for(int i=0; i<4; i++) {
authentication_key += (char) (rnd.nextInt('z'-'a'+1) + 'a');
}
System.out.println(authentication_key);
}
(1) 배열 선언
int[] arr;
(2) 선언되어진 배열을 메모리에 할당
arr = new int[5];
(3) 배열에 데이터 값을 넣어주기
arr[0] = 100;
arr[1] = 90;
arr[2] = 95;
arr[3] = 70;
arr[4] = 98;
(4) 출력
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}
public static void main(String[] args) {
int[] arr_1 = new int[] {100,90,95,70,98};
// 여기서 `new_int[]` 는 생략이 가능하다.
for(int i=0; i<arr_1.length; i++) {
System.out.println(arr_1[i]);
}
} // end of main
public static void main(String[] args) {
int[] arr_2 = {100,90,95,70,98};
// >>> 확장된 for문
for(int jumsu : arr_2) { // arr_2 배열의 길이 5만큼 반복한다.
System.out.println(jumsu);
// 첫번째 ... 다섯번째까지 반복하면서 값이 하나하나 다 들어옴.
}
}