猜数字游戏(Java Swing 界面实现)

来源:互联网 发布:php sendmail centos 编辑:程序博客网 时间:2024/06/15 14:19

Java写的文曲星猜数字游戏,系统会自动生成一个4位且每一位都各不相同的数字,当你猜测该数字时有A和B两种提示信息,其中A代表所猜数字中有该数字且位置也正确,而B代表所猜数字仅有该数字但是位置不正确。当猜对全部数字时即闯关成功(即4A0B)。

输入一个四位数都不相同的数字,系统会自动检查是否匹配,如果不匹配,就会输出一个nAnB的提示,要求玩家再输入一个数字。

package com.xujin;import java.util.ArrayList;import java.util.Random;import java.util.Scanner;public class Guess {Scanner cin = new Scanner(System.in);public static void main(String...args){Guess guess = new Guess();System.out.println("Welcome to the GuessNum game, enjoy it! ");//produce a new number which to guess.//利用一个ArrayList,随机在其中选取一个0~9的数,选完就在ArrayList中删除,然后继续在其中随机选取数字,直到4个全部选取完毕//initialize the ArrayListArrayList<Integer> array = new ArrayList<Integer>();for(int i = 0; i < 10; i++)array.add(i);Random random = new Random();for(int i = 0; i < 4; i++){int singleNumIndex = random.nextInt(arrayRange--);aimNum.add(array.get(singleNumIndex)); array.remove(singleNumIndex);}//test if the guess number equals to the aim number.while(true){guess.input();if(aimNum.equals(guessNum)){System.out.println("congratulations! You make it!");break;}guess.output();guessNum.clear();}}private void input(){int inputNum = cin.nextInt();for(int i = 0; i < 4; i++){guessNum.add(0, inputNum%10);inputNum = inputNum/10;}}private void output(){for(int i = 0; i < 4; i++)if(aimNum.get(i) == guessNum.get(i))aCount++;for(int i: aimNum)for(int j: guessNum)if(i == j)bCount++;bCount -= aCount;System.out.println(aCount + "A" + bCount + "B");aCount = 0;bCount = 0;}private static int seqNum = 0;private static int arrayRange = 10;  //上界,用于随机产生一个数组下标private static ArrayList<Integer> aimNum = new ArrayList<Integer>();private static ArrayList<Integer> guessNum = new ArrayList<Integer>();private static int aCount = 0;private static int bCount = 0;}


最近花时间把UI写了出来,界面如下,不好看,请见谅~~











源代码及install文件下载:http://download.csdn.net/detail/xujinsmile/5175683