如何在Java中重置循环中的变量?

时间:2015-11-05 19:16:39

标签: java for-loop

我正在为我的计算机科学1100课程编写一个数字猜谜游戏,其中一部分是打印玩家猜测目标数​​字时的尝试次数。我已经定义了一个变量tries来跟踪它;每当玩家猜测时,程序会将其递增1。

在玩家正确猜出数字后游戏重新开始,此时我想重置tries计数器。但是,我无法弄清楚如何做到这一点,因为每次猜到数字时程序都会递增tries。我该怎么办?

import java.util.Scanner;
import java.util.Random;
public class Q2 {
   public static void main(String[] args) {
      Scanner kbd = new Scanner(System.in);
      Random r = new Random();
      System.out.println("Welcome to the Number Guessing Game");
      int x=0;//defining x for later
      int tries = 1;//defining tries for later
      while (x!=-1) { 
         int y = r.nextInt(101);//defining random number 0-100
         System.out.print("Guess a number between 0 and 100 or enter -1 to quit: ");
         x=kbd.nextInt();//redefining x
         x=kbd.nextInt();//redefining x
         for (int i=1;x!=-1&&x!=y;i=1) {//for loop
               if (x<-1||x>100) {//illegal condition
                  System.out.print("Out of bounds. Try again: ");
               }
               else if (x>y) {//input greater than random condition
                  System.out.print("The number is lower. Try again: ");
               }
               else if (y>x) {//random greater than input condition
                  System.out.print("The number is higher. Try again: ");
               }
               x = kbd.nextInt();//redefining x
               tries+=i;//defining pattern for tries
         }
         if (x==y) {//input=random condition
            System.out.println("Congratulations! You guessed the number in " + tries + " tries");
         }
      }
      if (x==-1) {//quit condition
         System.out.print("Thank you for playing the game!!");
         }
     }
}

2 个答案:

答案 0 :(得分:8)

a)更改变量的范围

变量仅在其定义的范围内可用。例如

while (something) { // all code inside the loop is in an inner scope
  int variable = 42;
  // variable is accessible here
}
// variable is not accessible here

这意味着,每次while循环执行一次迭代时,都会新创建变量。最好只在实际具有含义的范围内定义变量(在本例中为while循环)。

b)每次重新分配变量

另一种方法是每次必要时重置变量。这将导致这样的设计:

int variable; // variable is defined outside the inner scope
while (something) {
  variable = 42;
  // some code that changes variable's value
}

答案 1 :(得分:0)

一种可能的解决方案是将猜测游戏封装到它自己的方法中,这将在调用时重新初始化所有变量,如果猜测正确,则在循环内部创建if条件。

private static void guessingGame() {
    Scanner scanner = new Scanner(System.in);
    double randomNum = Math.random();
    double tries = 0, guess = 0;

    do while (!(guess == randomNum) {
        System.in("What is your guess? ");
        guess = scanner.nextDouble();
        tries++;

        if (guess == randomNum) {
           System.out.println("Guessed correctly in " + tries + " tries.");
           tries = 0;
        }
    }
}

public static void main() {
   guessingGame();
}