Home > database >  Java: Value repeats in array from input of user
Java: Value repeats in array from input of user

Time:11-13

I have written a code to get values from users 5 times, but only allow to enter only unique values, However it does not work the right way ( The part validating if it is a unique value or no )

Here is code:

for (int answerUserTries = 0; answerUserTries < 5; answerUserTries  ) {
    System.out.println("Please enter the number");
    int answerUser = in.nextInt();
    for (int w=0;w<5;w   ) {
        if (answerArray[w] == answerUser) {
            System.out.println("Please enter the number REPEATING NUMBER");
            w=6;
        }
        else {
            answerArray[w] = answerUser;
        }
}

It work fine, but when I put non-unique value into array as a result it writes that it is non-unique value, however it only have 5 inputs, and when i put non-unique value input is also counts. How can i fix it? Here is result of running code:

Please enter the number
1
Please enter the number
1
Repeating Number
Please enter the number
1
Repeating Number
Please enter the number
1
Repeating Number
Please enter the number
1
Repeating Number

And then program stops

CodePudding user response:

You need to bump the counter only when you have success. You only need to search through as many answers as you have received, and you need to add your entry at answerUserTries, not at w:

int answerUserTries = 0;
while(answerUserTries < 5) {
    System.out.println("Please enter the number");
    int answerUser = in.nextInt();
    bool success = true;
    for (int w=0;w<answerUserTries;w   ) {
        if (answerArray[w] == answerUser) {
            System.out.println("Please enter the number REPEATING NUMBER");
            success = false;
            break;
        }
    }
    if( success ) {
        answerArray[answerUserTries] = answerUser;
        answerUserTries  ;
    }
}
  • Related