我试图制作程序/游戏,用户必须猜测数字为1-100。我知道如何使用随机类,但我必须使用Math.Random(学校项目)。我遇到的问题是我无法通过多个猜测使数字保持不变。生成一个随机数,但它会在每次猜测时发生变化,使其无意义。任何帮助表示赞赏。谢谢!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Guess implements ActionListener
{
JFrame f;
Container c;
JPanel p;
JTextField x;
JLabel title, out;
JButton guess;
int outp, num;
public Guess()
{
f = new JFrame("Guess a Number!");
f.setSize(230,190);
c = f.getContentPane();
p = new JPanel();
title = new JLabel("Guess a Number (1-10):");
x = new JTextField(10);
guess = new JButton("Guess");
guess.addActionListener(this);
out = new JLabel("");
p.add(title);
p.add(x);
p.add(out);
p.add(guess);
c.add(p);
f.show();
}
public void actionPerformed (ActionEvent event)
{
if(event.getSource() == guess)
{
outp = (int)((Math.random() * 100 + 1));
int numb = Integer.parseInt(x.getText());
if(numb > outp)
{
out.setText("Number is Lower");
}
if(numb < outp)
{
out.setText("Number is Higher");
}
if(numb == outp)
{
out.setText("Correct!");
}
}
}
}
答案 0 :(得分:3)
你的问题是你每次猜测都会重新生成一个新的随机数。简单地说
outp = (int)((Math.random() * 100 + 1));
进入构造函数,你将被设置。