作者luj810714 (清風曉明月)
看板C_Sharp
標題[問題] 並未將物件參考設定為物件的執行個體
時間Sun Mar 31 02:08:30 2013
老師給了一段單向佇列的code,要改成雙向佇列(其實也就是加上一個previous)
因為之前用C有寫過類似的作業,用一樣的邏輯寫也沒有bug
但是執行後卻一直顯示"並未將物件參考設定為物件的執行個體"
我只知道哪一段程式碼出了問題,但不知道發生了甚麼事
下面附上我的code,希望版上大大不吝指教
謝謝
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StackNodeTest
{
class Program
{
static void Main(string[] args)
{
String taken;
Stack s = new Stack(); ;
Console.WriteLine("Stack START:(Enter Number, '#' to End)\n-----");
do
{
taken = Console.ReadLine();
if (taken != "#")
{
s.push(int.Parse(taken));
}
} while (taken != "#");
do
{
int e;
s.pop(out e);
Console.WriteLine(e);
} while (s.checktop());
Console.Read();
}
}
class Stack
{
private Node Top;
private Node botton;
public Stack()
{
this.Top = null;
}
public bool push(int x)
{
Node p=new Node(x,Top);
this.Top.Setprevious(p);開發環境顯示這一行有問題
if (this.Top == null)
{
this.Top =this.botton = p;
}
else
{
this.Top = p;
}
return true;
}
public bool pop(out int x)
{
x = Top.getdata();
this.Top = Top.getnext();
return true;
}
public bool popfrombotton(out int x)
{
x = botton.getdata();
this.botton = botton.getprevious();
return true;
}
public bool checktop()
{
return this.Top != null;
}
}
class Node
{
private int data;
private Node next;
public Node previous;
public Node(int x, Node next)
{
Setdata(x);
Setnext(next);
this.previous = null;
}
public void Setdata(int x)
{
this.data = x;
}
public void Setnext(Node next)
{
this.next = next;
}
public void Setprevious(Node previous)
{
this.previous = previous;
}
public int getdata()
{
return this.data;
}
public Node getnext()
{
return this.next;
}
public Node getprevious()
{
return this.previous;
}
}
}
--
推 olduck:紅豆生南國12/25 16:07
推 newmatt: 春來發起痴12/25 16:56
推 asdfzx: 願插郭采潔12/25 17:34
推 otakuwill: 恥物最香濕12/25 17:39
推 a01000a:王摩詰-香濕12/25 18:10
推 jpsstargazer:前幾樓淫出好詩呀12/25 20:07
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 49.158.2.110
→ luj810714:最後我用try-catch把那一行隔離後不管exception message 03/31 03:20
→ luj810714:程式一樣可以執行,但我還是希望可以了解問題發生原因@@ 03/31 03:20
→ ssccg:因為this.Top一開始是null啊 03/31 04:22
→ ssccg:就在那下面不就正有檢查this.Top是不是null的code? 03/31 04:22
→ ssccg:那一樣使用this.Top的那行不也應該先確定是不是null? 03/31 04:26
推 Eleganse:這樣寫當然可以 加個try-catch沒啥問題 能跑就是正確程序 03/31 08:05
→ Eleganse:但是類別stack的建構函數stack()中 程式塞了個null給它 03/31 08:06
→ Eleganse:如果成員是null 程式還能正常跑不就活見鬼了 03/31 08:07
→ Eleganse:當然當你作了第1次PUSH後 裡面有值了 物件就開始正確運行 03/31 08:08
→ Eleganse:因此try-catch程序ok 只在物件初始化時 進了1次catch而已 03/31 08:09
→ Eleganse:不喜歡的話 那就把stack類別砍掉重練 03/31 08:11
→ Eleganse:依你自已的邏輯重寫 記得建構函數時要塞值進去 不要null 03/31 08:12
→ Eleganse:然後我剛才突然想到 System.Collections裡不是就有個 03/31 08:21
→ Eleganse:stack類別...那幹麻自已寫啊 03/31 08:21
→ luj810714:感謝!原來如此!!,但依我設計的邏輯是,當他POP時發現 03/31 21:18
→ luj810714:Top是null時就跳出do-while迴圈,那麼是否有其他替代方 03/31 21:19
→ luj810714:案呢? 03/31 21:19
→ ssccg:跟pop有什麼關係? 問題那行在push裡面啊 04/01 00:41
→ ssccg:把那行移到else裡面,this.Top = p; 上面就好了 04/01 00:41
→ ssccg:這明明是流程設計上有問題,因此加try-catch一點都不ok 04/01 00:42