通過調用Scanner類實現鍵盤導入數據,到程序中.
通過調用Random類產塵隨機數
猜數字游戲,有次數限制,代碼如下
public class Demo04RandomGame {
public static void main(String[] args) {
Random r = new Random();
int randomNum = r.nextInt(100) + 1;
Scanner sc = new Scanner(System.in);
//while循環
//int i = 0;
//while(true)
for (int i = 0;i <=5;i++) {
System.out.println("請輸入你猜測的數字:");
int guessNum = sc.nextInt();//鍵盤輸入猜測的數字
if (i == 5) {
System.out.println("Game over");
break;
}
if (randomNum > guessNum) {
System.out.println("太小了,請重試。");
} else if (randomNum < guessNum) {
System.out.println("太大了,請重試。");
} else {
System.out.println("恭喜你,猜對了。");
break;//如果猜中,不在重試,跳出循環
}
}
System.out.println("游戲結束。");
}
}
通過for循環 或者 while循環來限制循環次數