2013-11-21 66 views
0

我無法將字符串轉換爲int。我環顧四周,並被告知使用int.Parse,但它沒有幫助。使用streamreader時無法將字符串轉換爲int

我創建了一個對象Winner,它具有一個int WinnerScorestring WinnerName。 我想在排序它們之前將這些值添加到數組Winner[]

當我運行這段代碼,它說:

的NullReferenceException是未處理不設置到對象的實例

對象引用。

任何想法爲什麼會發生這種情況?

StreamReader sr = new StreamReader("highscores.txt"); 

for (int u = 0; u < nWinners; u++) 
{ 
    unsortedList[u].WinnerScore = int.Parse(sr.ReadLine()); 
    unsortedList[u].WinnerName = sr.ReadLine(); 
} 
sr.Close(); 
+4

請添加'unsortedList'的聲明和INITIALIZATION' – Steve

+1

如何初始化unsortedList數組?它在<0, nWinners>中看起來像unsortedList [u] = null – decPL

回答

2

有了一定的信心,我可以假設你已經聲明數組unsortedList但你沒有初始化要在該數組中存儲得主類的對象。

只是簡單地宣稱

Winner[] unsortedList = new Winner[100]; 

創建一個可以存儲得主的100個實例的數組,但這個數組是空的,也有贏家類中的100個插槽沒有的情況下,他們都是空。您應該創建每個想要在陣列的100個插槽中存儲的Winner實例。

所以,作爲一個例子,你的代碼可以改寫爲

Winner[] unsortedList = new Winner[nWinners]; 
using(StreamReader sr = new StreamReader("highscores.txt")) 
{ 
    for (int u = 0; u < nWinners; u++) 
    { 
     Winner w = new Winner(); 
     w.WinnerScore = int.Parse(sr.ReadLine()); 
     w.WinnerName = sr.ReadLine(); 
     unsortedList[u] = w; 
    } 
    sr.Close(); 
} 

但是,這有一個你需要知道的缺點,進入循環前,要求獲獎對象的確切數量DIMENSION的數組,如果由於某種原因,您無法正確計算它們,則會陷入另一個問題(索引超出範圍)。

在這種情況下,它始終是更好地使用List<Winner>,你不需要事先知道元素

List<Winner> unsortedList = new List<Winner>(); 
using(StreamReader sr = new StreamReader("highscores.txt")) 
{ 
    while((line = sr.ReadLine()) != null)) 
    { 
     Winner w = new Winner(); 
     w.WinnerScore = int.Parse(line); 
     w.WinnerName = sr.ReadLine(); 
     unsortedList.Add(w); 
    } 
    sr.Close(); 
} 
0
var unsortedList = new List<Winner>(); 

var nWinners = 100; 
using (StreamReader sr = new StreamReader("highscores.txt")) 
{ 
    for (int i = 0; i < nWinners; i++) 
    { 
     var winer = new Winner(); 
     winer.WinnerScore = int.Parse(sr.ReadLine()); 
     winer.WinnerName = sr.ReadLine(); 
     unsortedList.Add(winer); 
    } 
    sr.Close(); 
} 
0

你讓創作以及初始化的確切數目:

// My suggestion of unsortedList generic type 
public struct Winner { 
    public int WinnerScore; 
    public String WinnerName; 
} 

... 

// 1. You shoud create unsortedList: 
List<Winner> unsortedList = new List<Winner>(); 

// 2. You should also initialize the list with Winner instances 
for (int u = 0; u < nWinners; ++u) 
    unsortedList.Add(new Winner()); 

// 3. Only that you can fill unsortedList from file. 
// And you original code becames the correct one 
using (StreamReader sr = new StreamReader("highscores.txt")) { 
    for (int u = 0; u < nWinners; ++u) { 
    unsortedList[u].WinnerScore = int.Parse(sr.ReadLine()); 
    unsortedList[u].WinnerName = sr.ReadLine(); 
    } 
}