Java实现猜数游戏

Java实现猜数游戏

随机产生一个100以内的整数,十次机会猜中。
public static void main(String[] args) {
        //1.随机生成一个1-100的随机整数
        Random rand = new Random();
        int a = 1;
        int b = 100;
        int n = rand.nextInt(a, b + 1);

        int i = 0;
        //2.条件循环语句
        while (true) {
            if(i>=10){
                System.err.printf("%d、游戏结束,智商太低,游戏:(%d)分。%n", i, 0);
                break;
            }
            System.out.printf("请输入数字[%d-%d]:%n", a, b);

            //3.键盘输入数字
            int t = new Scanner(System.in).nextInt();
            ++i;

            if (t == n) {
                System.out.printf("%d、恭喜您,猜对了,你的游戏:(%d)分。%n", i, (100 - i * 10 + 10));

                //退出循环语句
                break;
            } else if (t > n) {
                System.out.printf("%d、太大了。%n", i);
            } else {
                System.out.printf("%d、太小了。%n", i);
            }
        }
    }

运行结果如下
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的Java猜数游戏的图形界面实现代码: ```java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GuessNumberGUI extends JFrame implements ActionListener { private JTextField inputField; private JLabel outputLabel; private int randomNumber; private int numGuesses; public GuessNumberGUI() { super("数字游戏"); randomNumber = (int) (Math.random() * 100) + 1; numGuesses = 0; JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 1)); JLabel promptLabel = new JLabel("输入一个 1 到 100 之间的整数:"); inputField = new JTextField(10); inputField.addActionListener(this); outputLabel = new JLabel("你还没有过。"); outputLabel.setHorizontalAlignment(SwingConstants.CENTER); panel.add(promptLabel); panel.add(inputField); panel.add(outputLabel); setContentPane(panel); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { int guess; String inputString = inputField.getText().trim(); try { guess = Integer.parseInt(inputString); } catch (NumberFormatException ex) { outputLabel.setText("输入必须是一个整数。"); return; } numGuesses++; if (guess == randomNumber) { outputLabel.setText("恭喜你对了!你一共了 " + numGuesses + " 次。"); inputField.setEnabled(false); } else if (guess < randomNumber) { outputLabel.setText("你小了。你已经了 " + numGuesses + " 次。"); } else { outputLabel.setText("你大了。你已经了 " + numGuesses + " 次。"); } inputField.setText(""); } public static void main(String[] args) { new GuessNumberGUI(); } } ``` 这个程序使用了Java的Swing库来创建一个简单的图形用户界面。程序生成一个 1 到 100 之间的随机数,并要求用户输入一个整数测这个随机数。每次用户测时,程序会告诉用户他们的数字是太大了还是太小了,直到用户对为止。程序还会记录用户测的次数,并在用户对时显示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值