Java版 猜数字小游戏
生活随笔
收集整理的這篇文章主要介紹了
Java版 猜数字小游戏
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
猜數(shù)字小游戲是一定是大家學(xué)習(xí)C語(yǔ)言編程的第一個(gè)或者是前幾個(gè)小小項(xiàng)目了吧,今天,我們使用Java進(jìn)行猜數(shù)字小游戲的實(shí)現(xiàn)
有對(duì)猜數(shù)字小游戲的基本思想不清楚的可以看這篇博客,里面是用C語(yǔ)言進(jìn)行的實(shí)現(xiàn)以及相關(guān)講解
c語(yǔ)言猜數(shù)字小游戲
話不多說(shuō),上代碼
import java.util.Random; import java.util.Scanner;class Game {// 開(kāi)始菜單public void menu() {System.out.println("*******************************************************************");System.out.println("************************* 猜數(shù)字小游戲 *****************************");System.out.println("******************** 0. 退出游戲 1. 開(kāi)始游戲 *********************");System.out.println("*******************************************************************");}// 生成隨機(jī)數(shù)public int random() {Random random = new Random();return random.nextInt(100)+1;}// 判斷輸入數(shù)字與隨機(jī)數(shù)之間的關(guān)系,大于返回大于0,小于返回小于0,等于返回0public int compare(int num, int random) {return num-random;}// 根絕 compare 返回的值輸出提示語(yǔ)句,并返回接下來(lái)是否繼續(xù)進(jìn)行, 猜對(duì)了返回1,游戲結(jié)束,猜錯(cuò)了返回0,游戲繼續(xù)public int message(int compare) {if(compare > 0) {System.out.println("太大了");return 0;} else if(compare < 0) {System.out.println("太小了");return 0;} else {System.out.println("猜對(duì)了");return 1;}}// 接受stdin輸入的字符,返回為對(duì)應(yīng)數(shù)字public int scanf() {System.out.print("請(qǐng)輸入:>");Scanner input = new Scanner(System.in);String str = input.next();int num = Integer.parseInt(str);return num;}// 邏輯函數(shù)public void realGame() {int num = 0;int flag = 0; do {menu();flag = scanf();switch(flag) {case 1: {// 開(kāi)始游戲int random = this.random();System.out.println(random);num = this.scanf();while(message(compare(num, random)) == 0) {num = this.scanf();}flag = 1; }break;case 0: {flag = 0;System.out.println("游戲退出");}break;default: {System.out.println("請(qǐng)輸入正確選項(xiàng)");flag = 1;}break;}}while(flag == 1);} }class PlayGame {// 在構(gòu)造方法里打印游戲開(kāi)始菜單private Game game = new Game();// 調(diào)用Game類中的游戲方法public void start() {game.realGame();}}public class Day5 {public static void main(String[] args) {/* System.out.println("input");if( str.equals("0")) {System.out.println(str);} else {System.out.println("hah");} */PlayGame game = new PlayGame();game.start();} }總結(jié)
以上是生活随笔為你收集整理的Java版 猜数字小游戏的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 拓扑排序- 基本思路
- 下一篇: 文本转拼音 麦谈帮API数据接口