你這么寫吧。拋一次骰子,就是你剛才那個,循環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])+"次");
}
}
}