자바에서 난수를 발생시키는 방법으로는 2가지 방법이 있다.
첫번째는 Math클래스의 random메서드를 이용하여 난수를 발생시키는 방법이다.
아래의 예제로 설명하자면, 0~1 사이의 double형 난수를 리턴한 후 * 10을 하고,
그 값을 int형으로 a,b,c,d,e에 반환하여 출력하는 것이다.
public class HelloWorld{ public static void main(String []args){ int a = (int) (Math.random()*10); int b = (int) (Math.random()*10); int c = (int) (Math.random()*10); int d = (int) (Math.random()*10); int e = (int) (Math.random()*10); System.out.println(a+","+b+","+c+","+d+","+e); } }
<결과>
두번째는 Random 클래스를 사용하는 방법이다.
Boolean nextBoolean()
float nextFloat() 등등
random.nextInt(100)을 입력하면, 0~100사이의 난수가 발생한다.
import java.util.Random; public class HelloWorld{ public static void main(String []args){ Random random = new Random(); int f = random.nextInt(10); int g = random.nextInt(10); int h = random.nextInt(10); int i = random.nextInt(10); int j = random.nextInt(10); System.out.println(f+","+g+","+h+","+i+","+j); } }
<결과>
반응형
'이것저것 배운것 > JAVA 공부중' 카테고리의 다른 글
JFrame에서 GUI 레이아웃 위치 조절시 (0) | 2015.09.29 |
---|---|
JButton으로 종료시키기 (0) | 2015.09.19 |
Static URL Path Download (0) | 2015.07.09 |
Java GUI. 프레임을 화면 중앙에 출력하기 (0) | 2015.06.02 |
JVM Option (0) | 2014.01.20 |