2016-01-20 52 views
-2

我该如何限制一个简单游戏的尝试只有三个?我想你会使用布尔值。但不确定。尝试进行简单游戏的次数有限?

import java.util.Scanner; 

public class guess { 

    public static void main(String[] args) { 
     int randomN = (int) (Math.random() * 10) + 1; 

     Scanner input = new Scanner(System.in); 
     int guess; 
     System.out.println("Enter a number between 1 and 10."); 
     System.out.println(); 

     do { 
      System.out.print("Enter your guess: "); 
      guess = input.nextInt(); 

      if (guess == randomN) { 
       System.out.println("You won!"); 
      } else if (guess > randomN) { 
       System.out.println("Too high"); 
      } else if (guess < randomN) { 
       System.out.println("Too low"); 
      } 
     } while (guess != randomN); 
    } 
} 
+0

您需要为已经取得的尝试次数的计数器,你需要增加对循环的每个迭代的计数器,你需要一个额外的退出条件添加到您的'做-while'环 – MadProgrammer

回答

1
int attempts = 0; 
do{ 
    attempts++; 
    .... 
}while(guess != randomN && attempts < 3); 
0

使用的标志。将其初始化为0.如果猜测正确,则将其重置为0.如果不是1,则在每次猜测之前,检查标记> 2。如果不允许继续,则如果是中断。

-1

您可以在猜测失败时递增。我相信变量应该位于循环之外。然后剩下的就是添加一部分,当猜测用完时通知用户失败。

public static void main(String[]args) { 
    int rNumber = (int)(Math.random() * 10) + 1; 
    Scanner input = new Scanner(System.in); 
    int guess; 
    int tries = 0; 
    int success = 0; 

    System.out.println("Enter a number between 1 and 10."); 
    System.out.println(); 
    do { 
     System.out.println("Enter your guess: "); 
     guess = input.nextInt(); 
     if(guess == rNumber) { 
      System.out.println("You guessed right! You win!"); 
      success++; 
     } else if (guess < rNumber) { 
      System.out.println("Too low"); 
      tries++; 
     } else if (guess > rNumber) { 
      System.out.println("Too high."); 
      tries++; 
     } 
    } while(tries != 3 && success != 1 || success != 1); 

} 
+0

这代码将仅在第一次猜测正确时退出... – sinclair

+0

好点。我太仓促了。 – sunnlamp

+0

现在它会继续如果你猜对了;-) – sinclair