【发布时间】:2019-11-20 15:37:21
【问题描述】:
我的 for 循环和计数器有问题,它应该将我添加的数字的每个值相加,并在 for 循环结束时询问我该值是什么。我添加了数字 2 来结束循环,所以我尝试在打印之前从总数中减去它,但它不起作用。 救命!
import java.util.*;
public class CountingCards {
public static void main(String[] args) {
Counting();
}
public static void Counting() {
Random rand = new Random();
int count = 0;
int sum = 0;
Scanner in = new Scanner(System.in);
for (int a = 0; a < 110; a++) {
int player = rand.nextInt((10) + 1);
System.out.println(" ");
System.out.println("You got this card: " + player);
System.out.println("What is the value of that card");
int answer = in.nextInt();
if (player == 1) {
if (answer == -1) {
System.out.println("That is CORRECT");
count = -1;
}
if (answer != -1) {
System.out.println("Sorry, that is INCORRECT");
count = -1;
}
}
if (player == 2) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 3) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 4) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 5) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 6) {
if (answer == -1) {
count = -1;
System.out.println("That is CORRECT");
}
if (answer != -1) {
count = -1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 7) {
if (answer == 0) {
count = 0;
System.out.println("That is CORRECT");
}
if (answer != 0) {
count = 0;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 8) {
if (answer == 0) {
count = 0;
System.out.println("That is CORRECT");
}
if (answer != 0) {
count = 0;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 9) {
if (answer == 0) {
count = 0;
System.out.println("That is CORRECT");
}
if (answer != 0) {
count = 0;
System.out.println("Sorry, that is INCORRECT");
}
}
if (player == 10) {
if (answer == 1) {
count = 1;
System.out.println("That is CORRECT");
}
if (answer != 1) {
count = 1;
System.out.println("Sorry, that is INCORRECT");
}
}
if (answer == -2) {
sum = sum - 2;
System.out.println("Your total count is: " + sum);
break;
}
sum = sum + count;
}
}
}
总和应该添加我在整个 for 循环中获得的所有计数器,并且每次都询问我,看看我给它们的答案是否每次都添加到总计数器中。太远了,我不知道为什么
【问题讨论】:
-
我认为你写了一些更简单的东西来理解你的代码是如何运行/工作的。我没有“得到”这个游戏,这是真的吗?还是您只是对其进行了修改以将其变成其他东西?无论如何,我还要做的是删除第二组 IF。如果您测试 if (answer == -1),则无需测试 if (answer != -1)。我知道它更直接,但它违反直觉/难以阅读。然后,如果一个玩家只能是 1..10 中的一个,你应该添加 else if,所以 if (player == 1) else if (player == 2)
-
目前还不清楚您要在这里做什么。它打印一个值,然后询问该值是什么,但它从不将猜测与初始值进行比较?你想总结什么?随机数的总值,猜错/正确的次数?