我需要制作一个程序:重复滚动3个骰子,直到双打滚动(任何两个是相同的)。每次显示值,然后显示获得双打所需的尝试次数。
问题在于它是永远存在的,并不能准确地告诉我它运行了多少次。
这是我到目前为止所拥有的。
public class ExtraProblem4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int first, second, third;
int counter = 0;
while(true) {
counter ++;
first = (int)(Math.random()*(6-1+1)+1);
second = (int)(Math.random()*(6-1+1)+1);
third = (int)(Math.random()*(6-1+1)+1);
System.out.println(first + "\t" + second + "\t" + third + "\t");
if (first == second || second == third || first == third) {
System.out.println("Double! It took " + counter + " tries to get it!");
}
else {
first = (int)(Math.random()*(6-1+1)+1);
second = (int)(Math.random()*(6-1+1)+1);
third = (int)(Math.random()*(6-1+1)+1);
System.out.println(first + "\t" + second + "\t" + third + "\t");
}
}
}
答案 0 :(得分:0)
你可能最好使用do-while而且..我也摆脱了一些冗余的代码行,比如if中的else。
public class ExtraProblem4
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int first, second, third;
int counter = 0;
boolean rolledDoubles; //initializes boolean variable to keep the loop going
do //use a do-while so it tests after each roll
{
rolledDoubles = false; //defines variable as false so it keeps looping
counter = counter + 1; // more reliable step
first = (int)(Math.random()*(6-1+1)+1);
second = (int)(Math.random()*(6-1+1)+1);
third = (int)(Math.random()*(6-1+1)+1);
System.out.println(first + "\t" + second + "\t" + third + "\t");
if (first == second || second == third || first == third)
{
rolledDoubles = true; //you rolled a double! This will stop the loop
System.out.println("Double! It took " + counter + " tries to get it!");
}
}
while(!rolledDoubles); //uses not operator with rolledDoubles so when rolledDoubles is true then we stop the loop, if false we keep going
}
}
答案 1 :(得分:-1)
public class ExtraProblem4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int first, second, third;
int counter = 0;
boolean isDoubles= false;
while (!isDoubles)
{
first = (int)(Math.random()*(6-1+1)+1);
second = (int)(Math.random()*(6-1+1)+1);
third = (int)(Math.random()*(6-1+1)+1);
System.out.println(first + "\t" + second + "\t" + third + "\t");
isDoubles= first == second || first == third || second == third;
counter++;
}
System.out.println("Double! It took " + counter + " tries to get it!");
}
}