這篇文章給大家分享的是有關(guān)如何使用java實(shí)現(xiàn)簡(jiǎn)單猜數(shù)字游戲的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
具體內(nèi)容如下
1.游戲分析:
游戲第一步:需要一個(gè)隨機(jī)數(shù),并且該隨機(jī)數(shù)有范圍;(java的包中有一個(gè)Random類可產(chǎn)生隨機(jī)數(shù),需要導(dǎo)入這個(gè)包,如下) 游戲第二步:猜數(shù)字的設(shè)計(jì),猜的次數(shù)為5次
2.編程實(shí)現(xiàn):
import java.util.Random;import java.util.Scanner;public class Guess_num { public static void main(String[] args) { System.out.println("歡迎進(jìn)入猜數(shù)字游戲!"); System.out.println("請(qǐng)輸入一個(gè)數(shù)字:(范圍是0-100)"); Random pc_game = new Random(); int pc_num = pc_game.nextInt(101);//隨機(jī)產(chǎn)生一個(gè)小于101的整數(shù) Scanner input = new Scanner(System.in); int count = 5;//猜的次數(shù),可自定義 while(count > 0) { System.out.println("您有"+count+"次機(jī)會(huì)!"); count--; System.out.print("請(qǐng)輸入猜的數(shù)字:->"); int user_num = input.nextInt(); if(pc_num == user_num) { System.out.println("you are right!"); count = 0; } else if(pc_num > user_num) { System.out.println("sorry, guess small!"); } else if(pc_num < user_num) { System.out.println("sorry, guess big!"); } } System.out.println("游戲結(jié)束!"); input.close(); }}
感謝各位的閱讀!關(guān)于“如何使用java實(shí)現(xiàn)簡(jiǎn)單猜數(shù)字游戲”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!