用JAVA编一个程序,很基本的,帮忙一下,课堂作业。 1)程序随机分配给客户一个1-100的整数

2024-11-25 02:28:48
推荐回答(3个)
回答1:

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

public class AddTest {

public static void main(String args[]){

boolean flag = true;
while(flag){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个1-100的整数");

//input 是接收控制台输入的整数
int input = scanner.nextInt();
//创建一个随机数对象
Random r = new Random();
//产生一个1-100的随机数
int temp = r.nextInt(99)+1;
//打印产生的随机数,可以注释掉,用于调试
System.out.println("产生的数是"+temp);
if(input==temp){
System.out.println("恭喜你猜对了");
}else if(input>temp){
System.out.println("对不起你猜大了");
}else{
System.out.println("对不起你猜小了");
}
}
}

}
这里没有进行用户输入的合法和不合法判断,只实现了基本的功能,不过够你作业用了

回答2:

public class Test extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;
private Random random = new Random();
private int a = 0;
private JPanel p1 = new JPanel();
private JPanel p2 = new JPanel();
private JPanel p4 = new JPanel();
private JPanel p5 = new JPanel();
private JTextField str = new JTextField(15);
private JButton ok = new JButton("确定");
private JButton cancel = new JButton("取消");

public Test() {
super("用户测试");
a = random.nextInt(100);
Container con = this.getContentPane();
con.setLayout(new GridLayout(5, 1));
con.add(getP1());
con.add(getP2());
con.add(getP4());
con.add(p5);
str.addActionListener(this);
ok.addActionListener(this);
cancel.addActionListener(this);
}

public JPanel getP1() {
p1.add(new JLabel("用户获得的随机数为: " + a));
return p1;
}

public JPanel getP2() {
p2.add(new JLabel("请输入:"));
p2.add(str);
return p2;
}

public JPanel getP4() {
p4.add(ok);
p4.add(cancel);
return p4;
}

public void actionPerformed(ActionEvent e) {
if (e.getSource() == ok) {
if (Integer.parseInt(str.getText().trim()) == a) {
JOptionPane.showMessageDialog(null, "猜对了");
dispose();
System.exit(0);
} else if (Integer.parseInt(str.getText().trim()) > a) {
JOptionPane.showMessageDialog(null, "猜大了");
str.requestFocus();
str.setSelectionStart(0);
str.setSelectionEnd(str.getText().length());
} else if (Integer.parseInt(str.getText().trim()) < a) {
JOptionPane.showMessageDialog(null, "猜小了");
str.requestFocus();
str.setSelectionStart(0);
str.setSelectionEnd(str.getText().length());
}
} else if (e.getSource() == cancel) {
dispose();
System.exit(0);
}
}

public static void main(String[] args) {
Test test3 = new Test();
test3.setVisible(true);
test3.setSize(300, 220);
test3.setResizable(false);
test3.setLocationRelativeTo(null);
test3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}改过了,看看这个

回答3:

两个都说的对啊,一个是CMD下的, 一个是面板的 swing的