【问题标题】:How to get a counter for a guessing game如何获得猜谜游戏的计数器
【发布时间】:2015-01-27 20:14:56
【问题描述】:

我正在尝试在我的程序中添加一个计数器来计算用户进行的猜测次数。我不知道该怎么做...

下面是我的代码:

import java.util.*;//imports the utilities
public class WordPyramid {
    public static void main(String[] args) {
            int n;
            Scanner kb = new Scanner(System.in);
            System.out.println("Making 3 random numbers…"); 
            System.out.println("What is the sum?");
            Random rn =new Random();
            int answer = rn.nextInt(10) + 1;
            int answera=rn.nextInt(10) + 1;
            int answerb=rn.nextInt(10) + 1;;
            int fans =answer+answera+answerb;
            while ((n = kb.nextInt()) != fans) {

                  System.out.println("Sorry, try again");
                  System.out.println("What is the sum?");
                }
            System.out.println("");

          }



    }

【问题讨论】:

  • int counter = 0;counter++ 猜测时
  • 我强烈推荐做一些Java教程

标签: java loops while-loop counter


【解决方案1】:

考虑在while 循环之外有一个新的int count = 0,并在循环内部使用count++ 之类的增量。

这将使您的 count 值在每次错误猜测时增加 1,或者在每次运行 while 循环时有效。

您可能会发现 this 以及 Java 教程的其余部分也提供了丰富的信息。

【讨论】:

    【解决方案2】:

    如果您想显示每个尝试编号,这里有一个简单的示例:

           int i=0;
            while ((n = kb.nextInt()) != fans) {
                  i++;
                  System.out.println("Try number : "+i);
    
                  System.out.println("Sorry, try again");
                  System.out.println("What is the sum?");
    
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多