랜덤 숫자 (난수 중에서 정수)를 만드는 방법은 크게 두 가지가 있다. 1. Random 객체 이용하기
2. Math.random 함수 이용하기
1. 1부터 10 사이의 임의의 수 Math 클래스의 random() 을 사용하여 1과 10 사이의 임의의 수를 구하는 코드는 다음과 같다.
이제 위의 코드를 조금 더 풀어서 설명해보도록 하겠다. 우선 Math 클래스의 random() 함수는 0.0과 1.0 사이의 범위에 속하는 하나의 double 값을 반환한다. 0.0 <= Math.random() < 1.0 여기에 10을 각각 곱하면 다음과 같다. 0.0 * 10 <= Math.random() * 10 < 1.0 * 10 0.0 <= Math.random() * 10 < 10.0 이것을 int형으로 변환시켜주면 다음과 같다. 0 <= (int)(Math.random() * 10) < 10 여기에 1을 더해주면 다음과 같다. 1 이상 11 미만이므로 정수로 1과 10 사이의 정수가 출력된다. 0+1 <= (int)(Math.random() * 10)+1 < 10+1 1 <= (int)(Math.random() * 10)+1 < 11 2. 임의의 주사위 수 위의 코드를 이용하여 임의의 주사위 숫자를 구하는 것도 다음과 같이 할 수 있다. 주사위는 1부터 6까지의 수이므로 다음과 같은 코드로 구현이 가능하다.
3. 임의의 문자 임의의 문자가 ascii 코드 상에서 연속적으로 존재한다는 특징을 이용한 것이다. 만약 영문의 대문자 중 한 문자를 얻고자 한다면 다음과 같은 코드로 구현할 수 있다.
간단하게 설명하자면 영문자가 총 26개이므로 26을 곱해준 것이고 대문자 ascii 코드가 65부터 시작하기 때문에 65를 더해준다. 여기서 위와 다른 점은 char형으로 형변환하기 전에 +65를 해주었다는 점이다. 만약 위와 같이 (char)(Math.random()*26)+65; 를 하였다면 +65를 할 때 int형으로 변환되므로 에러가 발생된다. Note that this approach is more biased and less efficient than a One standard pattern for accomplishing this is:
The Java Math library function Math.random() generates a double value in the range In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.
This returns a value in the range For example, if you want
This would return a value in the range Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.
You now will get a value in the range
But, this still doesn't include
And there you have it. A random integer value in the
range |