Math 클래스
- a의 절댓값은 a와 0의 거리
- a >= 0 일 경우 a의 절댓값은 a
- a < 0 일 경우 a의 절댓값은 -a
import java.lang.Math;
public class Driver {
public static void main(String[] args) {
System.out.println(Math.abs(-10));
System.out.println(Math.abs(8));
}
}
|
cs |
10
8
|
cs |
최솟값, 최댓값
- 두 값 중 더 큰 값을 구하는 메서드는 max
- 두 값 중 더 작은 값을 구하는 메서드는 min
import java.lang.Math;
public class Driver {
public static void main(String[] args) {
System.out.println(Math.min(4, 10)); // 최솟값
System.out.println(Math.max(4, 10)); // 최댓값
}
}
|
cs |
4
10
|
cs |
Random 클래스
- 임의의 값을 받아오기 위해서는 Random 클래스를 import 해야함
- 그러나 Math와는 달리 Random은 인스턴스를 생성해서 사용해야함
- 0 이상 n 이하의 랜덤 값을 받아오려면 Random 클래스에 있는 nextInt 메소드 사용하기
import java.util.Random;
public class Driver {
public static void main(String[] args) {
Random rand = new Random();
System.out.println(rand.nextInt(10)); // 0 이상 9 이하의 랜덤한 값
}
}
|
cs |
만약 0 이상 n 이하가 아닌 a 이상 b 이하의 랜덤 값을 받아오려면?
import java.util.Random;
public class Driver {
public static void main(String[] args) {
Random rand = new Random();
int min = 10;
int max = 30;
System.out.println(rand.nextInt((max - min) + 1) + min); // 10 이상 30 이하의 랜덤한 값
}
}
|
cs |
- 즉 rand.nextInt(21) + 10이 되고, 10~30 사이의 숫자가 출력됨
- rand.nextInt(n)은 0~n-1까지의 숫자 중 하나를 return함
'DEV > JAVA' 카테고리의 다른 글
자료형 | ArrayList (0) | 2022.01.02 |
---|---|
Wrapper Class (0) | 2021.12.29 |
변수 | final (0) | 2021.12.23 |
변수 | 기본형 vs 참조형 (0) | 2021.12.21 |
this (0) | 2021.12.18 |