2016-09-27 2 views
0

변환 프로그램에서 미리 정의 된 텍스트 파일에서 특정 행을 읽을 때 이름을 제공하기 위해 사전을 사용하고 있습니다. 그런 다음 "Rows"라는 다차원 배열을 만들면 오류가 발생합니다.동일한 키가 이미 추가 된 다음 행의 이름을 지정하려고 시도합니다.

동일한 키가있는 항목이 이미 추가되었습니다.

은 다음 코드 조각이 기록됩니다

 Dictionary<string, int> rows = new Dictionary<string, int>(); 

     // The file "read.txt" is being read 
     string[] lines = File.ReadAllLines("read.txt"); 

     int[] array = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 

     // In this section each line is being read and the spacing is removed 

     foreach (string s in lines) 
     { 
      string[] arr = s.Split(' '); // This line ables the program to differ between variables and numbers. 

      for (int i = 0; i < arr.Length; i++) 
      { 
       array[i] = Convert.ToInt32(arr[i]); // arr is now converted into a Int. 

       rows.Add("array" + i, array[i]); 

      } 
     } 

는 그런 오류를 디버깅하는 것은 다음 루프가 종료 발생합니다. 왜 오류가 나타나고 어떻게 수정합니까?

+2

단서 : 읽은 각 줄에 "행"을 추가하고 있습니다. 그리고 매번 색인은 0으로 시작합니다 ... – Pikoh

+1

따옴표 '다음 행 "이라는 이름의 다차원 배열 만들기 ... 사전은 * 다차원 배열이 아닙니다 *. 고유 키가있는 키 - 값 쌍의 모음입니다. 동일한 * 키 (이 경우 'array0')를 두 번 추가 할 수 없습니다. – Fabjan

답변

3

여러 행이있는 경우 "array" + i == array0에서 다시 시작합니다. 해당 항목은 이미 사전에 추가되어 있으므로 예외가 발생합니다.

줄 번호도 기억해야하므로 "array" + "line" + lineNumber + "row" + i 정도의 형식이어야합니다.

+0

그런 다음 두 개의 카운터 a (foreach 내에 'int a = 0;'a ++'로 생성)와 i (루프에서)를 사용하여 동일한 오류가 계속 표시됩니다. 코드는'rows.Add ("array"+ a + i, array [i]); ' –

+0

'a + i'는 정수로 끝날 수 있으므로 궁극적으로'a' 'i'는 '0'이다. 내 코드를 사용해보십시오. –

+0

동일한 오류가 발생했습니다. 코드는'rows.Add ("배열"+ "행"+ i + array ")" –

0

사전은 하나의 키만 허용합니다. 오류는 동일한 키를 두 번 추가한다는 의미입니다.

for 루프는 "array" + i을 키로 삽입합니다. foreach 루프의 두 번째 실행에서 i는 다시 0이므로 실제로는 "item0"을 두 번 삽입하고 예외가 발생합니다.

-1

다중 int를 사전의 키에 연결하려고합니다. 사전이를 위해 할 수 없습니다, 오히려이

Dictionary<string, List<int>> or Dictionary<string, HashSet<int>> 

당신이 키로 ("배열"+ i)를 사용하는 경우, int로 그것을 할 것입니다.

0이 많은 배열을 초기화하는 것은 그리 좋지 않습니다. 새로운 int [n]을 사용하십시오.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace StackOverflow 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     Dictionary<string, HashSet<int>> rows = new Dictionary<string, HashSet<int>>(); 

     // The file "read.txt" is being read 
     string[] lines = new string[] { "1", "2", "1 2"}; //File.ReadAllLines("read.txt"); 

     // In this section each line is being read and the spacing is removed 
     foreach (string s in lines) 
     { 
      string[] arr = s.Split(' '); // This line ables the program to differ between variables and numbers. 

      int[] array = new int[arr.Length]; 
      for (int i = 0; i < arr.Length; i++) 
      { 
       array[i] = Convert.ToInt32(arr[i]); // arr is now converted into a Int. 

       string key = "array" + i; 
       if (!rows.ContainsKey(key)) rows.Add(key, new HashSet<int>()); 
       rows[key].Add(array[i]); 
      } 
     } 

     foreach (string key in rows.Keys) 
     { 
      Console.WriteLine($"{key}: {String.Join(", ", rows[key])}"); 
     } 
    } 
    } 
} 

많은 추가 개선이 가능 : 이러한 작은 변화와

, 여기 내 업데이트 버전입니다.

+0

코드에서 항목을 버립니다. 그것이 OP가 원하는 것인지 확실하지 않습니다. –

+0

이것은 우리가 달성하기를 원하는 것에 달려 있으며 사전에있는 각 항목에 대해 고유 한 목록을 갖거나 그렇지 않습니다. 그렇지 않은 경우 List를 HashSet 대신 사용할 수 있습니다. –

+0

@PatrickHofman 출력이 이상합니다. 모든 배열은 같음 0 배열 1과 2는'array1 : 0 1'과'array2 : 0 1'으로 주어진다. 예상 출력은 모든 배열이'arrayX : 0 0 0 0 0 0 0 0 0이 될 것이다. 0 0 0' except 'array1 : 0 1 1 0 0 0 0 0 0 0 0 0' –

0

완전한 기능을 갖춘 솔루션을 원하는 사용자에게 유용합니다. 다른 답변을 조합하여 작동하는 코드가 있습니다. 그것은 가정하고있는 것을 돌려줍니다.

namespace test_read_txt 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     // A string is created for the 14 first element 


     Dictionary<string, int[]> rows = new Dictionary<string, int[]>(); 


     // The file "read.txt" is being read 
     string[] lines = File.ReadAllLines("read.txt"); 

     // In this section each line is being read and the spaceing is removed 
     int counter = 0; 

     foreach (string s in lines) 
     { 
      //Console.WriteLine(s); 
      string[] arr = s.Split(' '); // This line ables the program to differ between variables and numbers. 

      int[] array = new int[arr.Length]; 

      for (int i = 0; i < arr.Length; i++) 
      { 
       array[i] = Convert.ToInt32(arr[i]); // arr is now converted into a Int. 
      } 


      string key = "array_" + counter++; 
      rows.Add(key, array); 
      //ShowArray(array); 

     } 

     foreach (string key in rows.Keys) 
     { 
      Console.WriteLine($"{key}: {String.Join(" ", rows[key])}"); 
     } 


     Console.ReadLine(); 
    } 

    public static void ShowArray(int[] arr) { 
     foreach (var item in arr) { 
      Console.Write(item + "-"); 
     } 
     Console.WriteLine(); 
    } 
} 

}

읽기 파일은 bin에 있습니다 다음과 같습니다 텍스트 파일입니다 - 프로그램 폴더> 디버그 :

0 0 0 0 0 0 0 0 0 0 0 0 0 
0 1 1 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 

출력은 각 행은 같다 이름 array_0 ... array12를 가지는 int []. 즐겨!!