Java猜數 ٩꒰▽ ꒱۶⁼³₌₃
阿新 • • 發佈:2020-12-22
技術標籤:java
Java猜數小遊戲,下面分別用了兩種迴圈方式實現
do-while:
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int ranNum = random.nextInt(10);//隨機數範圍
int count=0;//計數
do {
System.out.println("輸入猜測數字:");
int guessNum = scanner.nextInt ();
if (guessNum==ranNum){
System.out.println("恭喜猜對了√");
break;
}else if (guessNum>ranNum){
System.out.println("猜大了,再猜");
count++;
if (count>3){
System. out.println("下次再來吧");
}
}else {
System.out.println("太小了,再猜");
count++;
if (count>3){
System.out.println("下次再來吧");
}
}
}while (count< 4);
}
for:
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int ranNum = random.nextInt(10);//隨機數範圍
System.out.println("輸入猜測數字:");
int guessNum = scanner.nextInt();
for (int i = 0; i <4 ; i++) {
if (guessNum==ranNum){
System.out.println("恭喜猜對了√");
break;
}else if (guessNum>ranNum){
System.out.println("猜大了,再猜");
guessNum = scanner.nextInt();
}else {
System.out.println("太小了,再猜");
guessNum = scanner.nextInt();
}
}
System.out.println("下次再來");
}
效果展示: