자바에서 난수를 구하는 방법
1. Math.random() 메서드를 이용하는 방법
2. Random 이라는 클래스를 생성해서 구하는 방법
System.out.println("기본 난수 5개발생");
for(int i=1;i<=5;i++)
{
double a=Math.random(); //0.0~1.0미만(0.xxx~0.9xxx)의 랜덤한 난수 발생
System.out.println(a);
}
System.out.println("0~9사이의 난수 5개 발생");
for(int i=1;i<=5;i++)
{
int a=(int)(Math.random()*10); //랜덤구하세요 하면 이 수식사용
//0~9까지의 난수 발생
System.out.println(a);
}
System.out.println("1~10사이의 난수 5개 발생");
for(int i=1;i<=5;i++)
{
int a=(int)(Math.random()*10)+1; //1~10까지의 난수 발생시키기 위해 double을 int로 형변환
System.out.println(a);
}
System.out.println("1~100사이의 난수 5개 발생");
for(int i=1;i<=5;i++)
{
int a=(int)(Math.random()*100)+1; //1~100까지의 난수 발생
System.out.println(a);
}
System.out.println("0~99사이의 난수 5개 발생");
for(int i=1;i<=5;i++)
{
int a=(int)(Math.random()*100); //0~99까지의 난수 발생
System.out.println(a);
}
int a=(int)(Math.random()90); //0~89까지의 난수 발생
int b=(int)(Math.random()45); //0~44까지의 난수 발생
Random r=new Random();
=> static이라는 매서드 안에서는 new로 생성안해도 되지만 99% new로 생성해서 사용
System.out.println("0~9사이의 난수발생");
for(int i=1;i<=3;i++)
{
int n=r.nextInt(10); //n.nextInt(10);==(int)(Math.random()*10)
//random은 int로 반환하기 때문에 int 변수=랜덤의 변수.nextInt();
// r은 임의의 이름
System.out.println(n);
}
System.out.println("1~10사이의 난수발생");
for(int i=1;i<=3;i++)
{
int n=r.nextInt(10)+1; //n.nextInt(10);==(int)(Math.random()*10)+1
System.out.println(n);
}
public static void main(String[] args) {
//랜덤 수를 발생시킨 후 그 숫자를 맞춰보자
Scanner sc=new Scanner(System.in);
//1~100사이의 랜덤수 발생(rnd)
int rnd=(int)(Math.random()*100)+1; //이 줄까지하고 실행하면 출력이 안되었지만 콘솔창에는 이미 랜덤 수가 있음
int su; //랜덤 수 맞출 입력 숫자
int cnt=0; // x번 안에 맞추게 하기 위해 count로 사용
// count 없이 하려면 for문 사용 count 있으려면 while문 사용
// 혹은 몇 번만에 맞췄는지 표시해주려면 count 필요
while(true)
{
cnt++;
//System.out.print("숫자: ");
System.out.print(cnt+": ");
su=sc.nextInt();
if(su>rnd)
System.out.println(su+"보다 작습니다");
else if(su<rnd)
System.out.println(su+"보다 큽니다");
else
{
System.out.println("맞았습니다 정답은 "+rnd+"입니다");
break;
}
}
### System.out.println("게임종료");