我正在尝试制作一个程序/游戏,用户必须猜测 1-100 的数字。我知道如何使用 random 类,但我必须为此使用 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!");
}
}
}
}
最佳答案
你的问题是,每次他们猜测时,你都会重新生成一个新的随机数。简而言之
outp = (int)((Math.random() * 100 + 1));
进入构造函数,你就会被设置。
关于java - Java.Math.Random().保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264911/