另外游戏围栏发布问题,在等式之前显示加号

时间:2015-11-01 22:55:25

标签: java

我正在制作一个加法游戏,但我唯一的问题是即使在它前面没有数字,添加符号也会在问题出现前不断出现。解决这个问题的最简单方法是什么?

  package addgame;
  import java.util.Random;
 import java.util.Scanner;
 public class AddingGame {
private static Scanner console;

public static void main (String[]args) {
System.out.println("We are going to play an adding game, you have 3 tries. Type your answer.");
equation(); 
}   
public static void equation() {
    int tries = 5;
    int points=0;
    Random rand = new Random ();
    while (tries>=3) {
    int totalnums = rand.nextInt(4)+1;
    int sumAns=0;
    for (int i=1; i<=totalnums+1;i++) {
    int nums= rand.nextInt(10)+1;
    System.out.print(" + "+nums ); 
    sumAns+=nums;
}
    System.out.print(" = ");
    console = new Scanner (System.in);
    int ans = console.nextInt();
    if(ans!=sumAns) {
        tries--;
    }
    else if(tries>=3) {
    points++;   
    }
    if(tries<3) {
            System.out.println("Game Over...");
            System.out.println("Points="+points+"\nBetter luck next time!");

        }
    }

  }
 }

1 个答案:

答案 0 :(得分:1)

除了您发布的内容之外,还有一些问题。

首先,当他们只有3次尝试时,不要使用tries = 5。目前还不清楚。如果您或其他人必须在以后查看此计划,该怎么办?你知道“尝试= 5”是什么意思吗?

如果您改为说

int triesLeft = 3;

模棱两可的少得多。从3开始,你的while语句也更简单。

while (triesLeft > 0) {

同样,有点不清楚你要添加多少个数字。正如您所注意到的,如果您添加的数字的数量为0或1,则在添加游戏中会出现问题。您的解决方案确实有效。但是,如果你这样做了......(我在这段代码中也包含了一个可能的问题解决方案。)

int numberOfAddends = rand.nextInt(4)+2;  //This assumes the maximum number of numbers you want to add is 5 (i.e. 3 + 2), and the minimum number is 2.
int sumAns = rand.nextInt(10)+1;  //Now note these two lines.
System.out.print(sumAns); //this will make sure the first number is printed before the + sign

for (int i=1; i < numberOfAddends;i++) { 
    //the inside of this for loop can stay the same.
}

请注意,现在更容易分辨出现在发生了什么。考虑是否有任何方法可以使其更清晰,这可能是值得考虑的。

过去这一点,你的代码真的只是小事。

while(triesLeft > 0) {
    .
    .
    .
    if(ans!=sumAns) {
        tries--;
    }
    else {  //the check you specified was only ever reachable when the condition you were checking is true. What you wrote was equivalent to else if (true). 
    points++;   
    }
}
System.out.println("Game Over..."); //You don't need a check for this when it is placed outside the while loop. 
System.out.println("Points="+points+"\nBetter luck next time!");