我的程序的目标是掷出两个六面骰子,然后将两个骰子相加(1000次),并打印出程序中掷出的数字'4‘的多少倍。我尝试在循环外部和内部使用math.random类,没有明显的区别,甚至一开始也没有使用for循环,我的目标是最终将输出调用到main方法,以便打印它。我听到的count4++可以用于这样的操作,除了一些错误导致我使用它。任何帮助、指导或建议都将不胜感激。我真的很抱歉没有最好的代码编写格式,技能,或常识,请注意,这是我第一年采取编程。我收到错误count4++;cannot be resolved,修复它的唯一方法是将它设置为0,这会毁掉我的程序,因为它总是打印0。
import java.io.*;
public class Delt {
public static void main (String args [] ) throws IOException {
int i;
int Sixside1;
int Sixside2;
int count4 = 0;
int [] data = new int [1000];
input (data);
System.out.println("The number of times '4' came up in the six sided dices is :" + count4);
}
public static void input (int num []) throws IOException {
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
String input;
System.out.println("Hello and welcome to the program");
System.out.println("In this program two six sided dices will be rolled and one eleven sided dice will be rolled (1000 times each");
System.out.println("The dices will be rolled to determine the odds of how many times the roll 4 comes up on both dies(Press any key to con't) ");
input = myInput.readLine ();
for (int i = 0; i < 1000; i++)
{
int Sixside1 = (int) (Math.random ()*(6-4) + 4);
int Sixside2 = (int) (Math.random ()*(6-4) + 4);
double total = Sixside1 + Sixside2;
if ( total == 4) {
// print amount of times 4 shows up in 1000 rolls, ??
count4++;
//return it to main method??
}
}
} }发布于 2013-03-20 07:45:28
您没有初始化本地变量count4 -这是必须完成的。在循环之前,您可以使用:int count4 = 0;。一个方法中的局部变量与另一个方法中的局部变量不同,所以我建议您将input()方法中的count4变量返回给main方法,并将其打印出来。
你也没有按照你期望的那样计算掷骰子,这意味着你永远得不到4的和。Math.random()返回一个介于0和1(独占)之间的随机数-所以你的骰子将是:(int) (0-0.999)*2+4=(int)(0-1.999)+4=(int)4-5.9999= 4-5。相反,请使用(int)Math.random()*6+1。
编辑:
public static void main(String[] args) throws Exception {
System.out.println(input());
}
public static int input () throws IOException {
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Hello and welcome to the program");
System.out.println("In this program two six sided dices will be rolled and one eleven sided dice will be rolled (1000 times each");
System.out.println("The dices will be rolled to determine the odds of how many times the roll 4 comes up on both dies(Press any key to con't) ");
myInput.readLine();
int count4=0;
for (int i = 0; i < 1000; i++)
{
if ( (int)(Math.random ()*6+1)+(int)(Math.random ()*6+1) == 4) {
count4++;
}
}
return count4;
} https://stackoverflow.com/questions/15512512
复制相似问题