循环运行时出现 Java 逻辑错误 : If/else counter incorrectly counting

标签 java loops if-statement logic accumulator

如果此内容太模糊,请告诉我:

我有一个循环可以编译并运行,但它没有按照我想要的方式执行。 我试图计算循环运行期间做出 if/else 选择的次数,然后显示做出该选择的次数。

选择有效,循环有效,但如果我将未选择的选项编码为 0,那么如果下次选择另一个选择,第一个选择的累积计数将返回到 0。或者两者都返回选择是累积的。

我有 4 个 if/else 问题,但它们的编码类似,行为方式相同。如果我能只修复一个,我就能修复其余的。

这是代码的相关部分。 (过去曾有人要求我,如果只有一部分出现问题,就不要编写太多代码。)

int choiceCount;
int choiceCount2;

       while(quitYn == 1)
  {

     System.out.println("I am ready for the next participant.");
     System.out.println("");
     System.out.println("");
     System.out.println("What would you rather have?");
     System.out.println("Enter 1 for Love or 2 for Money.");
     surveyChoice = input.nextInt();

     if(surveyChoice == 1)
     {
        choice = FIRST_PICK;
        message = "Love";
        choiceCount = ++ FIRST_CHOICE - 1;
        choiceCount2 = ++ SECOND_CHOICE - 3;
     }
     else if(surveyChoice == 2)
     {
        choice = SECOND_PICK;   
        message = "Money"; 
        choiceCount = ++ FIRST_CHOICE - 1;
        choiceCount2 = ++ SECOND_CHOICE - 2;
     }
     else 
     {
        choice = "Broken dreams";
        message = "Broken dreams";
        choiceCount = ++ FIRST_CHOICE - 2;
        choiceCount2 = ++ SECOND_CHOICE - 3;
     }
System.out.println(choiceCount + "Participants chose" + FIRST_PICK);
     System.out.println(choiceCount2 + "Participants chose" + SECOND_PICK);         

最佳答案

根据您对问题的理解,您需要这样的东西

int choiceCount = 0;
int choiceCount2 = 0;

while(quitYn == 1)
{

 System.out.println("I am ready for the next participant.");
 System.out.println("");
 System.out.println("");
 System.out.println("What would you rather have?");
 System.out.println("Enter 1 for Love or 2 for Money.");
 surveyChoice = input.nextInt();

 if(surveyChoice == 1)
 {
    choice = FIRST_PICK;
    message = "Love";
    choiceCount++;
 }
 else if(surveyChoice == 2)
 {
    choice = SECOND_PICK;   
    message = "Money";
    choiceCount2++;
 }
 else 
 {
    choice = "Broken dreams";
    message = "Broken dreams";

 }
 }
 System.out.println(choiceCount + "Participants chose" + FIRST_PICK);
 System.out.println(choiceCount2 + "Participants chose" + SECOND_PICK); 

关于循环运行时出现 Java 逻辑错误 : If/else counter incorrectly counting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39036867/

相关文章:

java - 如何通过Java的值来验证调用?

java - JAVA中带有多个条件的do while循环

java - 您可以使用增强的 for every 循环将元素添加到数组中吗?

java - 如何不重复else语句

Python-如何在 x 和 y 之间做一个 if 语句?

java - 向表中添加按钮 (java swt)

java - Java/Swing 中的翻书

java - 打印为 2D Java 的一维数组

c - 二维数组中的意外输出

java - 为什么我在 Java 中读取一个简单的文本文件时在 do while 循环中的 If 语句中得到 NullPointerException