【Java】猜数字小游戏

Java-Examples 专栏收录该内容
98 篇文章 2 订阅

闲来无事想到之前自己做的猜数字没有特点就写了这个程序,它主要是结合了数组,可以实现按位拆解来按位提示用户猜的高低,下面是代码:

import java.util.Random;
import java.util.Scanner;

public class GuessNumber3 {
	private static int count = 0;
	
	public static int[] save(int number, int[] numberArray) {
		int hundred = number/100;
		int decade  = (number-hundred*100)/10;
		int unit    = number-hundred*100-decade*10;
		numberArray[0] = hundred;
		numberArray[1] = decade;
		numberArray[2] = unit;		
		return numberArray;
	}
	
	public static void judge(int number) {
		if (number >= 100 && number <= 999) {
			return;
		} else {
			System.err.println("数据不合法,程序结束");
			System.exit(0);
		}
	}
	
	public static int rejudge(int[] numberArray1, int[] numberArray2, int i) {
		if (numberArray1[i] > numberArray2[i]) {
			System.out.println("第" + (i+1) + "位猜低了!");
		} else if (numberArray1[i] < numberArray2[i]) {
			System.out.println("第" + (i+1) + "位猜高了!");
		} else {
			System.out.println("恭喜你,第" + (i+1) + "位猜对了!");
			count++;
		}
		return count;
	}
	
	public static void main(String[] args) {
		System.out.println("是否猜数字?(Y/N)");
		Scanner scan = new Scanner(System.in);
		String choice = scan.next();
		
		while(choice.equalsIgnoreCase("Y")) {
			int[] setNumberArray = new int[3];
			int[] getNumberArray = new int[3];
			
			Random r = new Random();			
			int setNumber = r.nextInt(900)+100;
			judge(setNumber);
			save(setNumber, setNumberArray);

			System.out.println("你至多有5次机会猜数字~~~");
			System.out.println("请输入一个三位整数");
			
			for (int j= 0; j < 5; j++) {
				int getNumber = scan.nextInt();
				judge(getNumber);			
				save(getNumber, getNumberArray);
				count = 0;
			
				for (int i = 0; i < 3; i++) {
					rejudge(setNumberArray, getNumberArray, i);
				}
				
				if (count == 3) {
					System.out.println("恭喜你,你猜对了!");
					System.exit(0);
				}
				
				if (j == 4) {
					System.out.println("要猜的数是:" + setNumber);
				}
			}
			System.out.println("是否继续猜数字?(Y/N)");
			choice = scan.next();
		}
		scan.close();
	}

}
  • 1
    点赞
  • 0
    评论
  • 3
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值