2012-12-14 4 views
1

높은 점수를 저장하는이 프로그램에서 사용자는 한 행에 플레이어의 이름과 최고 점수를 입력해야합니다 (예 : "eric 87"). 사용자가 마지막 플레이어의 이름과 점수를 입력하면 입력 한 점수를 한 번에 모두 나열해야합니다. "eric 97"과 같은 문자열을 분리 할 때 어떻게해야할지 모르겠다. 어떤 도움을 주셔서 대단히 감사합니다!문자열 분할 및 배열

const int MAX = 20; 
static void Main() 
{ 
    string[ ] player = new string[MAX]; 
    int index = 0; 

    Console.WriteLine("High Scores "); 
    Console.WriteLine("Enter each player's name followed by his or her high score."); 
    Console.WriteLine("Press enter without input when finished."); 

    do { 
     Console.Write("Player name and score: ", index + 1); 
     string playerScore = Console.ReadLine(); 
     if (playerScore == "") 
      break; 
     string[] splitStrings = playerScore.Split(); 
     string n = splitStrings[0]; 
     string m = splitStrings[1]; 


    } while (index < MAX); 

    Console.WriteLine("The scores of the player are: "); 
    Console.WriteLine("player \t Score \t"); 

    // Console.WriteLine(name + " \t" + score); 
    // scores would appear here like: 
    // george 67 
    // wendy 93 
    // jared 14 
+0

이름과 점수를 따로 묻지 않는 이유가 있다고 생각합니다 (별칭 : 쉬운/게으름 옵션)? – Pharap

답변

3

코드를 보면 플레이어 배열을 사용하지 않은 것입니다. 그러나 더 많은 객체 지향 접근 방식을 제안합니다.

public class PlayerScoreModel 
{ 
    public int Score{get;set;} 

    public string Name {get;set;} 
} 

플레이어와 점수를 List<PlayerScoreModel>에 저장하십시오.

마지막 사용자와 점수가 입력되면 목록을 반복하면됩니다.

do { 
     Console.Write("Player name and score: ", index + 1); 
     string playerScore = Console.ReadLine(); 
     if (playerScore == "") 
      break; 
     string[] splitStrings = playerScore.Split(); 
     PlayerScoreModel playerScoreModel = new PlayerScoreModel() ; 

     playerScoreModel.Name = splitStrings[0]; 
     playerScoreModel.Score = int.Parse(splitStrings[1]); 
     playerScoreModels.Add(playerScoreModel) ; 

    } while (somecondition); 

    foreach(var playerScoreModel in playerScoreModels) 
    { 
     Console.WriteLine(playerScoreModel.Name +" " playerScoreModel.Score) ; 
    } 

필요에 따라 오류 검사를 제공하십시오.

+1

그것은 일했다, 고마워! – user1902342

+0

물론, 만족 스러울 때 받아 들일 수 있습니다;) –