java猜数字游戏代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java猜数字游戏代码相关的知识,希望对你有一定的参考价值。

java猜数字游戏代码

import javax.swing.UIManager;

public class MainClass


public MainClass()



public static void main(String args[])

try

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

catch (Exception exception)
new NumGuessing();



import java.util.ArrayList;

public class Methods


public Methods()



public static int[] RandomNum()

int guessNum[] = new int[4];
ArrayList Temp = new ArrayList();
for (int i = 0; i < 4; i++)
guessNum[i] = -1;

for (int i = 0; i < 4; i++)

do

float tempNum = (float)Math.random() * 10F;
if ((double)tempNum >= 9.5D)
guessNum[i] = 0;
else
guessNum[i] = Math.round(tempNum);
while (Temp.contains(Integer.valueOf(guessNum[i])));
Temp.add(Integer.valueOf(guessNum[i]));


return guessNum;


public static boolean CheckIsFourNum(String enterString)

boolean IsFourNum = true;
try

Integer.valueOf(enterString);

catch (NumberFormatException e)

IsFourNum = false;

if (enterString.length() != 4)
IsFourNum = false;
return IsFourNum;


public static String GetResult(int Num[], String enterString)

String resultString = "";
int rightInAll = 0;
int rightOnlyInNum = 0;
for (int i = 0; i < 4; i++)

if (Num[3 - i] == Integer.valueOf(enterString.substring(i, i + 1)).intValue())
rightInAll++;
for (int j = 0; j < 4; j++)
if (Num[i] == Integer.valueOf(enterString.substring(j, j + 1)).intValue())
rightOnlyInNum++;



resultString = (new StringBuilder(String.valueOf(rightInAll))).append("A").append(rightOnlyInNum).append("B").toString();
return resultString;


public static boolean IsGuessed(String guessString, String guessedStrings[])

boolean isGuessed = false;
for (int i = 0; i < guessedStrings.length; i++)
if (guessString.equals(guessedStrings[i]))
isGuessed = true;

return isGuessed;


public static boolean HasSameNum(String guessString)

boolean hasSameNum = false;
for (int i = 0; i < guessString.length(); i++)

for (int j = 0; j < guessString.length(); j++)

if (i == j || !guessString.substring(i, i + 1).equals(guessString.substring(j, j + 1)))
continue;
hasSameNum = true;
break;




return hasSameNum;



import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class NumGuessing
implements ActionListener


private JFrame frame;
private JPanel centerJPanel;
private JPanel southJPanel;
private JTextArea showArea;
private JTextField guessField;
private JButton commitJButton;
private Font font;
private boolean isOver;
private int guessTimeCount;
private int guessingNum[];
private String guessedNum[];

public NumGuessing()

isOver = false;
guessTimeCount = 0;
guessedNum = new String[10];
frame = new JFrame("NumGuessing");
frame.setSize(200, 300);
frame.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - frame.getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - frame.getSize().height) / 2);
font = new Font(null, 2, 15);
centerJPanel = new JPanel();
southJPanel = new JPanel();
showArea = new JTextArea("以下是你猜数字的结果:\n");
showArea.setFont(font);
showArea.setEnabled(false);
guessField = new JTextField(6);
guessField.setFont(font);
commitJButton = new JButton("Enter");
commitJButton.setFont(font);
frame.setLayout(new BorderLayout());
centerJPanel.setLayout(new GridLayout(1, 2));
centerJPanel.add(showArea);
southJPanel.add(guessField);
southJPanel.add(commitJButton);
frame.add(centerJPanel, "Center");
frame.add(southJPanel, "South");
frame.validate();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
commitJButton.addActionListener(this);
guessingNum = Methods.RandomNum();


public void actionPerformed(ActionEvent e)

String guessString = guessField.getText();
if (!isOver && guessTimeCount < 10)

if (Methods.CheckIsFourNum(guessString))

if (!Methods.IsGuessed(guessString, guessedNum))

if (!Methods.HasSameNum(guessString))

showArea.append((new StringBuilder(String.valueOf(guessString))).append(" ").toString());
showArea.append((new StringBuilder(String.valueOf(Methods.GetResult(guessingNum, guessString)))).append("\n").toString());
guessField.setText(null);
guessedNum[guessTimeCount] = guessString;
guessTimeCount++;
if (Methods.GetResult(guessingNum, guessString).equals("4A4B"))

isOver = true;
JOptionPane.showMessageDialog(null, "You Are The Winner");

if (guessTimeCount >= 10)

isOver = true;
JOptionPane.showMessageDialog(null, "你应经猜了十次,输了!");
guessField.setText(null);

else

guessField.setText(null);
JOptionPane.showMessageDialog(null, "你输入的数中有相同的数字,请重新填写。");

else

guessField.setText(null);
JOptionPane.showMessageDialog(null, "这个数字你已经猜过了!");

else

guessField.setText(null);
JOptionPane.showMessageDialog(null, "请输入一个四位数字");

else

guessField.setEnabled(false);


参考技术A http://hi.baidu.com/shy2850/blog/item/8193e4676e213529ab184cd0.html

Java猜数字游戏

【Java】猜数字游戏

猜数字游戏

游戏规则:
  • 已经给了一个未知整数,然后去猜测具体的数是什么。
    • 如果猜大了,则提示您猜的太大了;
    • 如果猜小了,则提示您猜的太小了。
代码实现:
import java.util.Random;
import java.util.Scanner;

public class RandomGame 
    public static void main(String[] args) 	
        Random r1 = new Random();
        //	生成一个0~100的随机整数
        int num = r1.nextInt(100);
//      System.out.println("正确的数字是:"+num);
        int cn;

        //	1.猜对才结束游戏      
        int counter = 0;	//	计数
        while(true)
            Scanner sc = new Scanner(System.in);
            System.out.print("请您输入要猜的数字:");
            cn = sc.nextInt();
            counter++;
            if (cn > num)
                System.out.println("您猜的太大了。");
            
            else if (cn < num)
                System.out.println("您猜的太小了。");
            
            else
                System.out.println("\\n\\t您猜对了!");
                System.out.println("\\t总共用了"+counter+"次");
                break;

            
        
        
		//	2.给定有10次机会。
//        System.out.println("您有10次机会!");
//        for (int i = 1; i < 11; i++) 
//            Scanner sc = new Scanner(System.in);
//            System.out.print("请您输入要猜的数字(第"+i+"次):");
//            cn = sc.nextInt();
//            if (cn > num)
//                System.out.println("您猜的太大了。");
//            
//            else if (cn < num)
//
//                System.out.println("您猜的太小了。");
//            
//            else
//                System.out.println("\\n\\t您猜对了!");
//                System.out.println("\\t总共用了"+i+"次");
//                break;
//            
//        
        
        System.out.println("Game Over ");

    


思路整理:

  1. 用Random来生成一个随机整数(0~100)
  2. 用Scanner来进行猜数字,循环来实现多次猜数字

以上是关于java猜数字游戏代码的主要内容,如果未能解决你的问题,请参考以下文章

用Java编程这个猜数字游戏

Java猜数字游戏

Java猜数字游戏

Java完成简单猜数字游戏

猜数字游戏 - Java版

java之猜数字游戏