Ryan Martin Ryan Martin - 3 months ago 15
Java Question

Java Logic error on run of loop: If/else counter incorrectly counting

Please let me know if this one is too vague:

I have a loop that compiles and runs but it doesn't perform as I would like.
I'm trying to count the times an if/else choice is made so long as the loop runs then display the number of times that choice has been made.

The choices work, The loop works, but if I code the choice not picked to be counted as 0, then if the other choice was picked the next time around the accumulated count of the first choice is returned to 0. Or both choices are accumulated.

I have 4 if/else questions but they are similarly coded to act the same way. If I can just fix one, I can fix the rest.

Here is the relevant parts of the code. (I have been asked in the past to not put so much code if only part is acting up.)

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);

Answer

As per your questions understanding, you need something like this

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);