Java学习小程序(5)猜数字游戏
生活随笔
收集整理的這篇文章主要介紹了
Java学习小程序(5)猜数字游戏
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
猜數字游戲,游戲規則:程序內置一個1到1000之間的數字作為猜測的結果,由用戶猜測此數字。分別用 while 和 do-while 語句實現。
import java.util.Scanner; public class NumberGuess {public static void main(String[] args) {Scanner scan = new Scanner(System.in);int num = (int)(Math.random()*1000+1); //生成隨機數System.out.println(num);//do-while語句int guess;do {System.out.println("猜吧!");guess = scan.nextInt(); //1、3if (guess == 0) { // 輸入0,退出break;}if(guess > num) { //循環條件System.out.println("太大了"); // 大小提示}else if(guess<num) {System.out.println("太小了");}}while(guess != num);if(guess==num) {System.out.println("恭喜你猜對了!");}else {System.out.println("下次再來吧!"); //輸入0,退出提示}//while語句/*System.out.println("猜吧!");int guess = scan.nextInt(); //循環變量初始化while (guess != num) {if (guess == 0) { // 輸入0,退出break;}if(guess > num) { //循環條件System.out.println("太大了"); // 大小提示}else {System.out.println("太小了");}System.out.println("猜吧!");guess = scan.nextInt(); //循環變量的改變} if(guess==num) {System.out.println("恭喜你猜對了!");}else {System.out.println("下次再來吧!"); //輸入0,退出提示}*/}}?
總結
以上是生活随笔為你收集整理的Java学习小程序(5)猜数字游戏的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java学习小程序(4)数列求和
- 下一篇: java美元兑换,(Java实现) 美元