你这么写吧。抛一次骰子,就是你刚才那个,循环3次,取1-6随机数,取版到5,然后youFive++;取不到5,meiFive++。你权这样抛10000次,用youFive/10000就很接近真的概率了。 但这是统计的思路,样本可能存在偏差,不知道你算这个概率为什么编程?你计算出3个骰子都没有5的概率用1减一下就好了,应该是这个吧1-(5/6)*(5/6)*(5/6)
㈡ Java如何编写骰子程序,急!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyGuess extends JFrame implements ActionListener{
Container cont;
String str;
int s;
int a;
int conut;
JButton jb1;
JButton jb2;
JTextField jtf1;
JLabel jl1;
public MyGuess(){
this.setTitle("Let's Play Game");
this.setSize(350,400);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
cont = this.getContentPane();
cont.setLayout(new GridLayout(3,1));
JPanel jp1 = new JPanel();
jp1.setLayout(new FlowLayout(FlowLayout.CENTER,0,20));
jp1.setBorder(BorderFactory.createTitledBorder("Your Guess"));
jtf1 = new JTextField(20);
jp1.add(jtf1);
cont.add(jp1);
JPanel jp2 = new JPanel();
jp2.setLayout(new FlowLayout(FlowLayout.CENTER,0,25));
jp2.setBorder(BorderFactory.createTitledBorder("Hint"));
jl1 = new JLabel("Let's Play HiLo");
jp2.add(jl1);
cont.add(jp2);
JPanel jp3 = new JPanel();
jp3.setLayout(new BorderLayout());
JPanel jp4 = new JPanel();
jp4.setLayout(new FlowLayout(FlowLayout.CENTER,30,5));
jb1= new JButton("Guess");
jb1.addActionListener(this);
jb2= new JButton("clear");
jb2.addActionListener(this);
jp4.add(jb1);
jp4.add(jb2);
jp3.add(jp4,BorderLayout.SOUTH);
cont.add(jp3);
num();
}
public void num(){
a=(int)(Math.random()*100);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==jb1){
if(conut<3){
try{
if(e.getSource()==jb1){
str = jtf1.getText();
s = Integer.parseInt(str); //把输入的字符串转成int型
jl1.setText(s+"是");
if(s>a){
JOptionPane.showMessageDialog(cont,"大了");
}
if(s<a){
JOptionPane.showMessageDialog(cont,"小了");
}
if(s==a){
JOptionPane.showMessageDialog(cont,"猜对了");
}
}
}
catch(Exception e1){
JOptionPane.showMessageDialog(cont,"请输入1-100之内的数");
}
}
else{
JOptionPane.showMessageDialog(cont,"您只有三次机会!");
}
conut++;
}
if(e.getSource()==jb2){
conut=0;
num();
System.out.println(a);
JOptionPane.showMessageDialog(cont,"重新开始!");
}
}
public static void main(String [] args){
MyGuess guess = new MyGuess();
guess.setVisible(true);
}
}
这是1-100的随机数.你自己改改吧..我以前写的.有GUI界面,处理过输入异常,只能猜三次!
㈢ 掷骰子模拟程序 Java
publicclassTestDieRoll{
privateclassDieRoll{
版privatefinalintDIES=6;
privateintroll(){
return(int)(Math.floor(Math.random()*DIES+1));
}
}
publicstaticvoidmain(String[]args){
DieRolld=newTestDieRoll().newDieRoll();
int[]arr=newint[6];
for(inti=0;i<1000;i++)
arr[d.roll()-1]++;
for(inti=0;i<arr.length;i++){
System.out.println("掷得"+(i+1)+"点的权次数为"+(arr[i])+"次");
}
}
}