2017-07-22 97 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語句在循環內部,並且無論多次打印它的消息,它都會比較數組中的所有數字。For循環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語句在循環內部,並且無論多次打印它的消息,它都會比較數組中的所有數字。

好的,這很明確。你必須嘗試這樣的代碼(但未能將它展示給我們):

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

謝謝,也很抱歉不清楚。 –