2017-07-22 13 views
-4
char userChoice; 

printf("Choose how you would like to search.\nEnter A to display all players information.\ 
      \nEnter N to search a player based on name.\nEnter J to search a player based on jersey number.\ 
      \nEnter P to search a player based on position.\nEnter your choice: "); 
scanf("%c", &userChoice); 

do 
{ 
    if (userChoice == 'A' || userChoice == 'a') 
    { 
     for (index = 0; index < count; index = index + 1) 
     { 
      displayPlayers(&players[index]); 
     } 
    } 

    if (userChoice == 'J' || userChoice == 'j') 
    { 
     int jerseyNumber; 

     printf("\nEnter jersey number for the player: "); 
     scanf("%i", &jerseyNumber); 

     for (index = 0; index <= MAX_PLAYERS; index++) 
     { 
      if (jerseyNumber == players[index].jerseyNumber) 
      { 
       // If the condition is met the singleDisplay function is called. 
       // Containing the array of struct 
       singleDisplay(&players[index]); 

      } 
     } 
    } 
    if (userChoice == 'N' || userChoice == 'n') 
    { 
     char playerName[LEN_NAME + 1]; 

     printf("\nEnter name for the player: "); 
     scanf("%s", playerName); 

     for (index = 0; index <= MAX_PLAYERS; index++) 
     { 
      if (strcmp(playerName, players[index].firstName) == 0) 
      { 
       singleDisplay(&players[index]); 

      } 
     } 
    } 

このコードのほとんどは文脈のためのものですが、私が抱えている問題は、入力したジャージーが見つからないというメッセージを出力するelse文を作成できません。問題は、else文がループの中にあり、配列のすべての数値を比較している間に何回何回でもメッセージを出力することです。IF文Cプログラミングのループの場合

+1

Cで 'switch'ステートメントを調べるべきです。ここでうまくいくでしょう。 – lurker

+0

'for(index = 0; index BLUEPIXY

+0

「else文」がありません。あなたの質問をもう一度読んでください。 –

答えて

2

あなたが投稿したコードの関連部分のみがこれです:

for (index = 0; index <= MAX_PLAYERS; index++) 
    { 
     if (jerseyNumber == players[index].jerseyNumber) 
     { 
      singleDisplay(&players[index]); 
     } 
    } 

そして、あなたの質問にのみ関連する部分はこれです:

ユーザーにメッセージを出力elseステートメントこと彼らが入ったジャージーは見つからなかった。問題は、else文がループの中にあり、配列のすべての数値を比較している間に何回何回でもメッセージを出力することです。

OK、これは明らかです。あなたはこのようなコードを試してみました(しかし、私たちにそれを示すことに失敗)している必要があります。それが見つかった場合はもちろん

for (index = 0; index <= MAX_PLAYERS; index++) 
    { 
     if (jerseyNumber == players[index].jerseyNumber) 
     { 
      singleDisplay(&players[index]); 
     } 
     else 
     { 
      printf("no match for jersey number\n"); 
     } 
    } 

をエラーメッセージがMAX_PLAYERS回、または多分MAX_PLAYERS - 1回印刷されます。だから、あなたが明示的にこれを避けるために、あなたのコードを変更する必要があります。

int found = 0; 
    for (index = 0; index <= MAX_PLAYERS; index++) 
    { 
     if (jerseyNumber == players[index].jerseyNumber) 
     { 
      singleDisplay(&players[index]); 
      found++; 
      break; 
     } 
    } 
    if (!found) 
    { 
     printf("no match for jersey number\n"); 
    } 

breakが任意であるが、それはあなたがすでに試合を見つけたら以上の数字をチェック避けるために良い形です。つまり、同じジャージー番号を持つ複数のプレーヤーをサポートしたい場合を除き、その場合はbreakを削除します。

+0

ありがとうございます。 –

関連する問題