I'm attempting to write an error statement to tell the user that the "Player is not in roster". I'm using an if and else-if statement but when the else-if statement is true the print gets ignored and loops back to my defined menu. For the question about what is jerseyNumber. it is int jerseyNumber[100];
.
int jerseyNumber[100];
...
//case r allows for a player to be replaced
case 'r':
printf("Enter a jersey number:\n");
int replace;
scanf("%d", &replace);
if (replace == jerseyNumber) {
for (int i = 0; i < numPlayers; i) {
//if the user input matches a jersey in the array the user will input a new jersey number and rating
printf("Enter a new jersey number:\n");
scanf("%d", &jerseyNumber[i]);
printf("Enter a rating for the new player:\n");
scanf("%d", &playerRating[i]);
}
}
else if (replace != jerseyNumber) {
printf("Player not in roster.");
}
break;
CodePudding user response:
Since jerseyNumber
is an array (i.e. int jerseyNumber[100]
) this
if (replace == jerseyNumber) {
is comparing an int
with a pointer. That's a bug. You need to access an array element before the compare. Like
if (replace == jerseyNumber[SomeNumber]) {
This leads to the second problem. Your if
statement must be inside the for
loop like:
for (int i = 0; i < numPlayers; i) {
if (replace == jerseyNumber[i]) {
Further, you want to print a message when the number isn't found. There are several ways to do that. Here is one. The idea is simply to let the for
loop go one beyond the valid array size and then check for end-of-array inside the for
for (int i = 0; i <= numPlayers; i) { // note the <=
if (i == numPlayers) { // check for end-of-array
printf("Player not in roster\n"); // no more array elements
}
else if (replace == jerseyNumber[i]) { // check for jersey match
printf("Enter a new jersey number:\n");
scanf("%d", &jerseyNumber[i]);
printf("Enter a rating for the player:\n");
scanf("%d", &playerRating[i]);
break; // stop the loop
}
}
Bonus info
Always check the value returned by scanf
So your scanf
should be:
if (scanf("%d", &replace) != 1)
{
// Input error - no integer available
... add error handling here ...
}
CodePudding user response:
Use should use else
in place of else if
else {
printf("")
}
I don't know is it gonna work in c but it works in java so i think they are similar
Edit: The if
in the else if
is redundant in this case because it is testing the exact opposite of previous if
which had to be false if the program reach this point.