java #22 꼭 알아야 할 클래스와 메소드-3- (수학, 난수 관련)
* 수학 , 난수 관련 클래스
용도 | 클래스 | 특성 | 예제 |
수학 | math | - 객체화가 되지 않는 클래스 - 생성자가 private이라 api에 나오지 않음 - 클래스.method()로 사용.(static method) | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | - 절대값 Math.abs(값) - sin Math.sin(값) - cos Math.cos(값) - tan Math.tan(값) - 반올림(소수점 이하 첫째자리) Math.round(실수) : 정수 출력 - 올림 Math.ceil(실수) : 정수 출력 - 내림 Math.floor(실수) : 정수 출력 - 난수 Math.random() : 16~17자리수의 double값 출력 ex) 범위 5개의 난수 : (int)(Math.random()*5) | cs |
|
난수 | random | - 난수를 얻기 위해 만들어진 클래스
| | - 생성 Random r = new random(); - 정수난수 r.nextInt(); // -2147483648~+2147483647 출력 Math.abs(r.nextInt()%10); // 0~9 출력 r.nextInt(범위의수); // 범위의 수 출력 -실수 난수 (int)(r.nextFloat() *범위수); (int)(r.nextDouble() *범위수); -불린 난수 r.nextBoolean() // true, false 중 임의의 난수 | cs |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package day0228; import java.util.Random; public class UseRandom { public UseRandom(){ //객체생성 Random random = new Random(); //정수의 난수 얻기 int i=random.nextInt(); System.out.println("정수 난수 : "+i); //범위의 수 발생(%범위의 수) System.out.println("정수 난수 : "+(i%10)); System.out.println("정수 난수 : "+Math.abs(i%10)); int j=random.nextInt(10); System.out.println("정수 난수 : "+j); float f=random.nextFloat(); double d=random.nextDouble(); System.out.println("float 난수 : "+f); System.out.println("double 난수 : "+d); System.out.println("double 난수 범위 : "+d*10); System.out.println("double 난수 범위(정수만 출력) : " +(int)(d*10)); boolean b=random.nextBoolean(); System.out.println("boolean 난수 " +b); } public static void main(String[] args) { new UseRandom(); } } |
|