如果此内容太模糊,请告诉我:
我有一个循环可以编译并运行,但它没有按照我想要的方式执行。 我试图计算循环运行期间做出 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/