2016-09-13 8 views
-2

IndexOutOfRangeException was unhandledint euros = int.Parse(values[1]) 오류가 발생합니다.IndexOutOfRangeException 처리되지 않았습니다

내 .csv 파일은 같습니다

name, 1, 2 
name1, 3, 4 
name2, 5, 6 

public static void ReadData(out Turistai[] tourists, out int amount) 
    { 
     amount = 0; 
     tourists = new Turistai[MaxTourists]; 
     using (StreamReader reader = new StreamReader("C:\\Users\\Andrius\\Desktop\\Mokslams\\C#\\Pratybos\\P2\\P2.1\\turistai.csv")) 
     { 
      string line = null; 
      while((line = reader.ReadLine()) != null) 
      { 
       string[] values = line.Split(';'); 

       string name = values[0]; 
       int euros = int.Parse(values[1]); 
       int cents = int.Parse(values[2]); 
       Console.WriteLine(euros); 
       //Turistai tourists = new Turistai(name, euros, cents); 
       amount++; 
      } 
     } 
    } 
+0

안녕 안드리 될 것입니다. 귀하의 게시물을 닫으려는 투표를했습니다. 여기에서 유용한 질문에 대한 정보는 How to Ask 페이지를 참조하십시오. 기본적으로 코드 덤프 뒤에 암시 적 또는 명시 적으로 "나에게 이것을 해결하십시오"라는 게시물이 표시됩니다. 대신 디버거를 사용하여 코드를 단계별로 실행해야합니다. – ray

+0

은 @ray said : 디버거를 사용하고, 커서를'string [] values ​​= line.split (';');'로 설정하고, F9를 누르고 F5로 가라. 그런 다음 단계별로 진행할 수 있습니다. 'values' 위로 커서를 옮기고 내용을 봅니다. – Radinator

답변

0

귀하의 CSV 입력 쉼표 코드에서 당신이 세미콜론에 의해 분할하는 동안 분리. 변경 split() 매개 변수 ,에 :

string[] values = line.Split(','); 

당신은 또한 values 어레이는 적어도 세 가지 항목을 포함하고 숫자 필드는 실제로 정수 값을 (int.TryParse()이에 도움이 될 수 있습니다)를 포함 할 수 있도록 입력 형식 검사를 추가 할 수 있습니다 :

while((line = reader.ReadLine()) != null) 
{ 
    string[] values = line.Split(','); 
    if (values.Length < 3) 
    { 
     Console.Error.WriteLine("Invalid input line: " + line); 
     continue; 
    } 

    string name = values[0]; 
    int euros; 
    if (!int.TryParse(values[1], out euros)) 
    { 
     Console.Error.WriteLine("Invalid euros value in the line: " + line); 
     continue; 
    } 
    int cents; 
    if (!int.TryParse(values[2], out cents)) 
    { 
     Console.Error.WriteLine("Invalid cents value in the line: " + line); 
     continue; 
    } 
    Console.WriteLine(euros); 
    //Turistai tourists = new Turistai(name, euros, cents); 
    amount++; 
} 
+0

죄송합니다. 실수로 잘못된 기호를 넣었습니다. 문제는 동일하게 유지됩니다. 동일한 오류가 발생합니다. 편집 : 실제로 지금, 그것은 "FormatException 처리되지 않았습니다"라고 - 입력 문자열 양식이 올바른 형식이 아닙니다. – Andrius

+0

그런 다음 CSV 파일에 잘못된 형식의 행이있을 가능성이 큽니다. 그러한 수표로 답변을 업데이트했습니다. –

+0

잘못된 숫자 값으로 인해 "FormatException was unhandled"입니다. 그것을 확인하기 위해'int.TryParse()'를 사용하십시오. 업데이트 된 답변을 참조하십시오. –

0

아마도 CSV 파일에 몇 개의 빈 줄이 있습니다. 나는 유로를 정리해 Linq를을 사용하는 것이 좋습니다 :

var data = File 
    .ReadLines("C:\\Users\\Andrius\\Desktop\\Mokslams\\C#\\Pratybos\\P2\\P2.1\\turistai.csv") 
    .Select(line => line.Split(',')) 
    .Where(items => items.Length >= 2) // filter out empty/incomplete lines 
    // To debug, let's take euros only 
    .Select(items => int.Parse(items[1])); 
    // In the final solution we'll create Touristai instances 
    // .Select(items => new Touristai(items[0], int.Parse(items[1]), int.Parse(items[2]))) 
    .ToArray(); 

Console.WriteLine(String.Join(Environment.NewLine, data)); 

Console.WriteLine(data.Sum()); 

최종 솔루션

public static void ReadData(out Turistai[] tourists, out int amount) { 
    tourists = File 
    .ReadLines(@"C:\Users\Andrius\Desktop\Mokslams\C#\Pratybos\P2\P2.1\turistai.csv") 
    .Select(line => line.Split(',')) 
    .Where(items => items.Length >= 2) // filter out empty/incomplete lines 
    .Select(items => new Touristai(items[0], int.Parse(items[1]), int.Parse(items[2]))) 
    .ToArray(); 

    //TODO: check syntax (I've sugested Touristai should have Euro property) 
    amount = tourists.Sum(tourist => tourist.Euro); 
}