[ 작업 환경 ]
Windows10
jdk-15
1. RandomNumbers.java 소스 작성
//********************************************************************
// RandomNumbers.java Java Foundations
//
// Demonstrates the creation of pseudo-random numbers using the
// Random class.
//********************************************************************
import java.util.Random;
public class RandomNumbers
{
//-----------------------------------------------------------------
// Generates random numbers in various ranges.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);
num1 = generator.nextInt(10);
System.out.println ("From 0 to 9: " + num1);
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println ("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println ("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println ("A random float (between 0-1): " + num2);
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println ("From 1 to 6: " + num1);
}
}
2. 프로그램 실행 예시
javac RandomNumbers.java
java RandomNumbers.java
3. 연습해보기
// 문제
아래와 같이 int 타입의 변수 a와 b를 선언했다고 하자.
int a = 10;
int b = 20;
Random number r을 a <= r <= b 범위를 만족하도록 생성하는 java 프로그램을 작성하시오.
//********************************************************************
// RandomNumbers.java Java Foundations
//
// Demonstrates the creation of pseudo-random numbers using the
// Random class.
//********************************************************************
import java.util.Random;
public class RandomNumbers
{
//-----------------------------------------------------------------
// Generates random numbers in various ranges.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Random generator = new Random();
int num1 = 10;
float num2 = 20;
float r;
// 0 ~ 1 랜덤 변수 출력
r = generator.nextFloat();
System.out.println ("A random integer: " + r);
// 10 ~ 20 랜덤 정수 출력
r = generator.nextInt(11) + 10;
System.out.println ("From 10 to 20: " + (int)r);
// 10~20 랜덤 실수 출력
r = generator.nextFloat() * 10 + 10;
System.out.println ("From 10.00000 to 20.00000: " + r);
}
}
4. 연습해보기 실행 예시
javac RandomNumbers.java
java RandomNumbers.java