public static void ex01() { double randomNumber = Math.random(); // 0.0 <= 난수 < 1.0 // 확률 처리하기 if(randomNumber < 0.1) { System.out.println("대박"); } else { System.out.println("꽝"); } }
1단계 : Math.random() 0.0 <= n < 1.0
2단계 : Math.random() * 3 0.0 <= n < 3.0
3단계 : (int)(Math.random() * 3) 0 <= n < 3
4단계 : (int)(Math.random() * 3) + 1 1 <= n < 4
-----------------------------------------------------
(int)(Math.random() * 개수) + 시작값
(int)(Math.random() * 개수 + 시작값)
public static void ex02() { int randomNumber = (int)(Math.random() * 3) + 1; // 1부터 3개의 난수 발생 System.out.println(randomNumber); }
전달된 시드(seed)에 따라서 서로 다른 난수를 발생한다.
전달된 시드(seed)가 없는 경우에는 현재 시간을 시드(seed)로 사용한다.
동일한 시드(seed)를 사용하면 동일한 난수가 발생한다.
public static void main(String[] args) { // Random 객체 선언 & 생성 Random random = new Random(); // 실수 double randomNumber1 = random.nextDouble(); // 0.0 <= n < 1.0 // 정수 int randomNumber2 = random.nextInt(); // Integer.MIN_VALUE <= n <= Integer.MAX_VALUE int randomNumber3 = random.nextInt(5); // 0 ~ 4(5개 난수) System.out.println(randomNumber1); System.out.println(randomNumber2); System.out.println(randomNumber3); }
public static void main(String[] args) { // SecureRandom 객체 선언 & 생성 SecureRandom secureRandom = new SecureRandom(); // 실수 난수 double randomNumber1 = secureRandom.nextDouble(); // 정수 int randomNumber2 = secureRandom.nextInt(); int randomNumber3 = secureRandom.nextInt(5); System.out.println(randomNumber1); System.out.println(randomNumber2); System.out.println(randomNumber3); }
전역 고유 식별자(Universal Unique IDdentifier)
라는 뜻이다.UUID값은 String으로 바꿔서 사용
한다.public static void main(String[] args) { UUID uuid = UUID.randomUUID(); String str = uuid.toString(); System.out.println(str); }
어떤 정보를 읽어 들일 때 사용한다.
파일, 사용자 입력 정보 등을 읽어 들일 수 있다.
사용자가 입력하는 데이터의 타입에 따라서 입력 메소드가 구분되어 있다.
int
: nextInt();
long
: nextLong();
double
: nextDouble();
String
next()
nextLine()
사용자 입력을 위해서 사용해야 하는 입력 스트림(InputStream)은 System.in
이다.
public static void main(String[] args) { // Scanner 객체 선언 & 생성 Scanner sc = new Scanner(System.in); // String 입력 System.out.println("이름을 입력하세요"); String name = sc.next(); // 이름에 공백이 없어야 한다. System.out.println("입력된 이름: " + name); // int 입력 System.out.println("나이를 입력하세요"); int age = sc.nextInt(); System.out.println("입력된 나이: " + age); // double 입력 System.out.println("키를 입력하세요"); double height = sc.nextDouble(); System.out.println("입력된 키: " + height); // 사용한 입력 스트림 종료(생략 가능하다.) sc.close(); }
좋은 글 감사합니다. 자주 올게요 :)