Java實(shí)現(xiàn)簡(jiǎn)單猜數(shù)字小游戲
本文實(shí)例為大家分享了Java實(shí)現(xiàn)猜數(shù)字游戲的具體代碼,供大家參考,具體內(nèi)容如下
完成猜數(shù)字游戲需要實(shí)現(xiàn)以下幾點(diǎn):
獲得一個(gè)隨機(jī)數(shù)作為“答案數(shù)”; 輸入數(shù)字,與“答案數(shù)”作比較(判斷大了,小了,相等); 循環(huán)輸入所猜的數(shù)字,直到與“答案數(shù)”相等時(shí)游戲結(jié)束;代碼實(shí)現(xiàn):
import java.util.Random;import java.util.Scanner;public class guessNum { public static int getRanNum(){ //獲得一個(gè)隨機(jī)數(shù) Random random = new Random(); return random.nextInt(100); } public static boolean guess(Scanner scanner,int toGuess){ System.out.println('請(qǐng)輸入要猜的數(shù)(1-100):'); int num = scanner.nextInt(); if ( num < toGuess){ System.out.println('小了...'); return false; } else if ( num > toGuess){ System.out.println('大了...'); return false; } else { System.out.println('恭喜你,猜對(duì)了??!'); return true; } } public static void startGame(Scanner scanner){ int toGuess = getRanNum(); while( true ){ if (guess(scanner,toGuess)){ break; } } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); startGame(scanner); }}
運(yùn)行結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP基礎(chǔ)知識(shí)VBScript基本元素講解2. IntelliJ IDEA導(dǎo)入jar包的方法3. Python requests庫(kù)參數(shù)提交的注意事項(xiàng)總結(jié)4. ajax請(qǐng)求添加自定義header參數(shù)代碼5. vue-electron中修改表格內(nèi)容并修改樣式6. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)7. 詳談ajax返回?cái)?shù)據(jù)成功 卻進(jìn)入error的方法8. python操作mysql、excel、pdf的示例9. SpringBoot參數(shù)校驗(yàn)與國(guó)際化使用教程10. JavaScript中l(wèi)ayim之整合右鍵菜單的示例代碼
