자바 문법
자바 Up & Down 게임 만들기
Nickman
2024. 3. 28. 00:45
랜덤으로 수를 결정하여 맞추는 코드를 작성하였다. 수의 범위를 지정 해 주는데, 배열을 사용하지 않고 변수 s(더 낮은 경우)와 j(더 높은 경우)를 이용하여 작성하였다.
package grammer;
import java.util.Scanner;
import java.util.Random;
public class updown {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);
Random r= new Random();
int k=r.nextInt(100);
int j=99;
int i=2;
int s=0;
System.out.printf("수를 결정하였습니다. 맞추어보세요.\n%d-%d\n1>>\n",s,j);
int a=sc.nextInt();
do {
if(a<k) {
System.out.printf("더 높게\n%d-%d\n%d>>",a,j,i);
i++;
s=a;
}else if(a>k){
System.out.printf("더 낮게\n%d-%d\n%d>>",s,a,i);
i++;
j=a;
}
a=sc.nextInt();
}while(a!=k);
System.out.printf("맞았습니다.\n다시 하시겠습니까(y/n)>>");
String text=sc.next();
if(text.equals("n")){
sc.close();
}else if(text.equals("y")) {
main(args);
}
}
}