220614 TIL

Yeoni·2022년 6월 14일
0

국비교육TIL

목록 보기
10/41

국비교육 10일차 Java : 랜덤으로 숫자 뽑기, 배열

1. 랜덤으로 숫자 뽑아내기

1) Math.random

랜덤한 정수 = (int) (Math.random()*구간범위) + 시작값;
System.out.println("1부터 10까지 랜덤으로 정수 뽑기 => " + ( (int) (Math.random()*(10-1+1)) + 1) );

2) Random(이 방법 더 추천, Math.random은 보안상 위험)

Random rnd = new Random();
// 객체 생성 Random rnd 후 rnd.nextInt(마지막수-처음수+1) + 처음수;
		
System.out.println("1부터 10까지 랜덤으로 정수 뽑기  => " + ( rnd.nextInt(10-1+1) + 1) );

2) 숫자 3개와 소문자 4개로 이루어진 인증 키

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);
	
}

2. 배열(array)

  • 배열이란?
    일한 데이터 타입을 가지는 여러 개의 데이터를 저장할 수 있는 데이터 타입을 말한다. 그리고 배열 또한 객체(instance)라는 것을 꼭 기억하도록 하자.

1) 배열 형식 1

(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]);
}

2) 배열 형식 2

  • 위에 했던 배열을 동시에 간략하게 실행하면 다음과 같다.
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

3) 배열 형식 3

  • 확장 for문 이용하기
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); 	
        // 첫번째 ... 다섯번째까지 반복하면서 값이 하나하나 다 들어옴. 
	}
}	
profile
이런 저런 기록들

0개의 댓글