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. Python的文本常量與字符串模板之string庫(kù)2. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)3. 利用CSS制作3D動(dòng)畫4. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程5. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))6. Springboot 全局日期格式化處理的實(shí)現(xiàn)7. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法8. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題9. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼10. JAMon(Java Application Monitor)備忘記
