본문 바로가기
카테고리 없음

남들이 만들어 놓은 좋은 기능 가져다 쓰기 (메서드 & Math)

by 쿠키오빠 2024. 9. 2.
반응형

메서드를 이용한 Math 호출 (남들이 만들어 놓은 좋은 기능을 가져다 쓸 수 있음)

        /* index. 1. 절대값 출력 해보기 */
        System.out.println("-7의 절대값 구하기 : " + (Math.abs(-7))); // 마우스 대고 + ctrl + 클릭 누르면 누군가 만들어 놓은 공식으로 이동

        /* index. 2. 최대값과 최소값 출력 해보기 */
        // 최대값
        System.out.println("10과 20중 더 큰 값은 ? : " + Math.max(10, 20));
        // 최소값
        System.out.println("10과 20중 더 큰 값은 ? : " + Math.min(10, 20));

        /* index. 3. 난수 출력 */
        System.out.println("랜덤 값 출력 : " + Math.random());

아래의 코드는 int 형으로 강제 형 변환 (공식은 자주 쓰이므로 외워두는 게 좋다)

        /* comment. 난수의 활용
        *   math.random()을 이용하게되면 0부터 1전까지의 실수 값을 반환해 준다. */

        /* comment. 원하는 범위의 난수를 구하는 공식 (int)(Math.random() * 구하려는 난수의 개수) + 구하려는 난수의 최소값 */
        /* index. 1. 0 ~ 9까지의 난수 발생 */
        int random1 = (int)(Math.random() * 10) + 0;
        System.out.println("random1 = " + random1);

        // 1 ~ 10
        int random2 = (int)(Math.random() * 10) + 1;
        System.out.println("random2 = " + random2);

        // 10 ~ 15
        int random3 = (int)(Math.random() * 6) + 10;
        System.out.println("random3 = " + random3);

        // -128 ~ 127
        int random4 = (int)(Math.random() * 256) - 128;
        System.out.println("random4 = " + random4);

하지만 위의 공식보다 더 특화되고 간단한 공식이 있다.

위의 공식은 강제 형변환도 해야하고 공식이 복잡한데, 더 간단하고 특화된 공식은 아래 코드로 확인해보자

package com.ohgiraffers.section03.math;

import java.util.Random; //메서드 이전 클래스와 같이 난수 생성 연습인데 이번 클래스는 조금 더 특화된 클래스.
                            // '(int)(Math.random() * 구하려는 난수의 개수) + 구하려는 난수의 최소값' 보다 'random.nextInt(구하려는 난수의 개수) + 구하려는 난수의 최소값'가 더 간소

public class Application3 {

    public static void main(String[] args) {

        /* title. java.util.random 클래스를 사용해서 난수 발생 */

        Random random = new Random();
        /* comment. random.nextInt(구하려는 난수의 개수) + 구하려는 난수의 최소값; */
        int randomNumber = random.nextInt(10);
        System.out.println("randomNumber = " + randomNumber);

        // 1 ~ 10
        int randomNumber2 = random.nextInt(10);
        System.out.println("randomNumber2 = " + randomNumber2);
        // 10 ~ 15
        int randomNumber3 = random.nextInt(6);
        System.out.println("randomNumber3 = " + randomNumber3);
        // -127 ~ 128
        int randomNumber4 = random.nextInt(256);
        System.out.println("randomNumber4 = " + randomNumber4);


    }
}

메서드 선언과 같이, Random random = new Random(); 이런식으로 선언을 해주고 변수명 지정하고 바로 사용 가능하다.

난수 말고도 이런 식으로 남들이 만들어 놓은(public) 기능들을 편리하게 사용할 수 있다

많이 이용해 보자!!

반응형