循环运行时Java逻辑错误:If/else计数器计数不正确
如果这个太模糊,请告诉我: 我有一个编译和运行的循环,但它并没有像我希望的那样执行。 我试图计算在循环运行期间做出if/else选择的次数,然后显示做出该选择的次数 选项起作用,循环起作用,但如果我将未拾取的选项编码为0,那么如果下次拾取了另一个选项,则第一个选项的累积计数将返回0。或者两种选择都是累积的 我有4个if/else问题,但它们的编码类似,以相同的方式进行操作。如果我能修好一个,我就能修好其余的 下面是代码的相关部分。(过去有人要求我,如果只有一部分出了问题,就不要写那么多代码。)循环运行时Java逻辑错误:If/else计数器计数不正确,java,loops,if-statement,logic,accumulator,Java,Loops,If Statement,Logic,Accumulator,如果这个太模糊,请告诉我: 我有一个编译和运行的循环,但它并没有像我希望的那样执行。 我试图计算在循环运行期间做出if/else选择的次数,然后显示做出该选择的次数 选项起作用,循环起作用,但如果我将未拾取的选项编码为0,那么如果下次拾取了另一个选项,则第一个选项的累积计数将返回0。或者两种选择都是累积的 我有4个if/else问题,但它们的编码类似,以相同的方式进行操作。如果我能修好一个,我就能修好其余的 下面是代码的相关部分。(过去有人要求我,如果只有一部分出了问题,就不要写那么多代码。)
根据你的问题理解,你需要这样的东西
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);
请解释此代码:
choiceCount=++FIRST_CHOICE-1似乎您只需要choiceCount++代码>但也许我遗漏了什么?看起来像java,请添加java标记。如果我在每个部分都添加了选择计数,那么即使没有选择,我也会得到一个计数。我试图让它知道什么时候不计数,什么时候计数。只有这样,我才会得到一个错误,即变量choiceCount可能没有初始化,因为else if和else选项中没有提到它。对于未初始化的变量choiceCount
或choiceCount2
,使用答案中的代码。它与您问题中的代码的不同之处在于,在声明变量的地方,它们被初始化为值0。答案中的第一行代码为int choiceCount=0
初始化choiceCount
以获得值0
。我没有将choiceCount更改为0,我错过了该值。我删去了多余的代码,简化了它。多亏了Sandesh和Evan
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);