【发布时间】:2020-11-27 01:45:51
【问题描述】:
我用 Java 创建了一个 RandomSumGame,需要提供输赢的数量。我试图在方法中添加计数的打印,但它在每场比赛后打印出来,而不是在最后打印出来。我将打印件移到了主类,但我无法让它打印其他类的总数。
下面是我的程序
package Question4;
import java.util.Random;
public class RandomSumGame {
boolean start;
int d1;
int d2;
int sum = d1 + d2;
int valuePoint;
String status = "+";
public void play (int d1, int d2) {
sum = d1 + d2;
int countW = 0;
int countL = 0;
for (;;) { //Part I. of question
if (sum == 2 || sum == 3 || sum == 12) {
start = false;
System.out.println(" = " + sum + "\nCRAPS! You lose!");
countL++;
break;
}
else if (sum == 7 || sum == 11) { //Part II. of question
start = true;
System.out.println(" = " + sum + "\nNATURAL! You win!");
countW++;
break;
}
valuePoint = sum;
if (valuePoint == 4 ||valuePoint == 5 || valuePoint == 6 || valuePoint == 8
|| valuePoint == 9 || valuePoint == 10) { //Part III. of question
System.out.println(" = " + valuePoint + "\nA value point of " + valuePoint
+ " has been established. Roll again.");
break;
}
}
for (;;) {
if (sum == 7) { //exception to valuepoint is 7
break;
}
else {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
int a1 = d1;
System.out.print("You rolled\n" + "\t" + d1);
for (int x = 0; x < 1; x++) {
d2 = 1 + rand.nextInt(6);
int a2 = d2;
int sum = a1 + a2;
System.out.println(" " + status + " " + d2 + " = " + sum);
}
}
sum = d1 + d2;
if (sum == valuePoint) { //if sum equals valuepoint established
start = true;
System.out.print("\t" + "You win!" + "\n");
countW++;
break;
}
else if (sum == 7) {
start = false;
System.out.print("\t" + "You lose! " + "\n");
countL++;
break;
}
}
}
}
public void play () {
for (int x = 0; x < 3; x++) {
rolldice();
play(d1, d2);
System.out.print("\n");
}
}
public void rolldice() {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
System.out.print("You rolled " + d1 + " " + status);
}
for (int i = 0; i < 1; i++) {
d2 = 1 + rand.nextInt(6);
System.out.print(" " + d2 + " ");
}
}
}//end of class
这是我的主线
package Question4;
public class TestRandomSumGame {
public static void main(String[] args) {
System.out.println("Craps is a dice game where two dice are rolled."
+ " The dice are added together and; \nIf the sum is 7 or 11, you win!"
+ "\nIf the sum is 2, 3, or 12, you lose!"
+ "\nIf the sum is 4, 5, 6, 8, 9, or 10, a valuepoint is established which is"
+ "\nwhere you contine to roll the dice until you roll the same number"
+ " (you win)"
+ "\nor a 7 (you lose)."
+ "\nThe game will run for 3 plays.\n");
RandomSumGame test = new RandomSumGame();
test.play();
System.out.println("Wins: " + countW + "\nLosses: " + countL);
}
}//end of class
我确定我遗漏了一些简单的东西,但我似乎无法解决这个问题。
【问题讨论】:
-
你不在这里错过
test吗?System.out.println("Wins: " + test.countW + "\nLosses: " + test.countL);。考虑到这些属性是公开的。
标签: java class variables printing