[問題] 並未將物件參考設定為物件的執行個體

看板C_Sharp作者 (StarLight)時間13年前 (2011/03/26 00:32), 編輯推噓1(104)
留言5則, 4人參與, 最新討論串3/9 (看更多)
在下剛開始學C#幾週 是要寫一個初學者都會碰到的猜數字(nAnB) 本來想說自己可以寫出來 不過卡在最後一個點想了兩三個小時 也查了許久還是無解 因此來板上請教 以下是部份code(一個for loop內): string Resp = sr.ReadLine(); if (Resp.Length != 4) { sw.WriteLine("Error 3: The number of digit is incorrect."); } 這個猜數字是用StreamReader讀取測值然後把回應用StreamWriter輸出的 卡住的這個點是要檢測一個error 也就是輸入位數不符(非四位數) 但debug的時候就出現了 「並未將物件參考設定為物件的執行個體。」 爬文了一下發現似乎與value不能是null有關 在下自己測了一下覺得應該是因為讀取(sr)的關係讓Resp.Length出了問題 但礙於自己是初學者實在不懂要如何解決這個問題 到MSDN搜尋到了也是看的很吃力 希望板上前輩指教... 感恩 ========================================================================== 小弟還是補一下完整的code 這樣可能比較容易找到問題在哪 static void Main(string[] args) { StreamReader sr = new StreamReader("file path"); StreamWriter sw = new StreamWriter("file path"); string input = sr.ReadLine(); //讀入答案 Int32 Dig4 = Int32.Parse(input) / 1000; Int32 Dig3 = Int32.Parse(input) % 1000 / 100; Int32 Dig2 = Int32.Parse(input) % 1000 % 100 / 10; Int32 Dig1 = Int32.Parse(input) % 1000 % 100 % 10; //用取餘數拆成個、十、百、千位數 int LineCount = 0; while (sr.Peek() >= 0) { sr.ReadLine(); LineCount++; } //計算行數 for (int i = 0; i < LineCount; i++) { string Resp = sr.ReadLine(); if (Resp.Length != 4) { sw.WriteLine("Error 3: The number of digit is incorrect."); } //確認讀入的測值的位數是否正確(四位數) else { int Res = Int32.Parse(Resp); int dig4 = Res / 1000; int dig3 = Res % 1000 / 100; int dig2 = Res % 1000 % 100 / 10; int dig1 = Res % 1000 % 100 % 10; //將測值拆解 if (dig4 == 0) { sw.WriteLine("Error 1: The leftmost digit is “0”."); } //最左位數不得為0 else if (dig1 == dig2 || dig1 == dig3 || dig1 == dig4 || dig2 == dig3 || dig2 == dig4 || dig3 == dig4) { sw.WriteLine("Error 2: Digit is re-used."); } //輸入的四個數字中不得出現重複的數字 //用繁複的土法煉鋼寫成的nAnB else { int A = 0, B = 0; if (dig1 == Dig1) { A++; } if (dig2 == Dig2) { A++; } if (dig3 == Dig3) { A++; } if (dig4 == Dig4) { A++; } if (dig1 == Dig2) { B++; } if (dig1 == Dig3) { B++; } if (dig1 == Dig4) { B++; } if (dig2 == Dig1) { B++; } if (dig2 == Dig3) { B++; } if (dig2 == Dig4) { B++; } if (dig3 == Dig2) { B++; } if (dig3 == Dig1) { B++; } if (dig3 == Dig4) { B++; } if (dig4 == Dig2) { B++; } if (dig4 == Dig3) { B++; } if (dig4 == Dig1) { B++; } sw.WriteLine(A + "A" + B + "B\n"); } } } sw.Close(); Console.ReadLine(); } 不好意思code雖然簡單但是很冗長 因為三天前才開始學陣列所以沒有使用陣列來寫 麻煩各位了._. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.231.65.222

03/26 00:44, , 1F
http://pastie.org/1714208 試試看加這個 if
03/26 00:44, 1F
※ 編輯: jerry50714 來自: 118.231.65.222 (03/26 01:13)

03/26 03:02, , 2F
你算行數時已經把sr讀到底了 正式來的時候只會讀到null
03/26 03:02, 2F

03/26 09:35, , 3F
原來如此! 沒想到這點!
03/26 09:35, 3F

03/26 09:43, , 4F
感謝樓上兩j大和a大 多new一個sr總算解決了!
03/26 09:43, 4F

03/29 01:39, , 5F
為看先猜你的input文件最後面有新行字串
03/29 01:39, 5F
文章代碼(AID): #1DZCEIcv (C_Sharp)
討論串 (同標題文章)
文章代碼(AID): #1DZCEIcv (C_Sharp)