Re: [問題] JAVA新手的問題...
※ 引述《mantos730.bbs@ptt.cc (饅頭)》之銘言:
: 我是個初學JAVA的新手,過去較常接觸C語言
: 在C語言中,我常常自訂一個struct,然後再定義一個陣列,type是讓struct
: 例如:
: struct element{
: int key;
: };
: 之後在程式中使用 element node[10] 便可分別存取
: node[0].key
: node[1].key.....
: 但在使用java後,我試著自訂一個類別,並想定義一個陣列,type是該類別
: 例如:
: class element{
: public int key;
: }
: 之後在main中使用 element[] node = new element[10]...但似乎行不通....
: 不知道是不是我的語法錯誤還是怎樣,麻煩各位高手教教我吧,感激不盡!!
你宣告的是一個物件陣列,每個物件使用前應該要先new一個instance
請參考:
//File Test1.java
public class Test1 {
public static void main(String[] args) {
Element[] node = new Element[10];
for(int iIdx = 0;iIdx<10;iIdx++){
node[iIdx] = new Element();
node[iIdx].key = iIdx;
System.out.println(node[iIdx].key);
}
}
}
class Element{
public int key;
}
or
//File Test.java
public class Test {
public static void main(String[] args) {
Element[] udtE = {new Element(),new Element(),new Element()};
for(int iIdx = 0;iIdx<3;iIdx++)
udtE[iIdx].key = iIdx;
for(Element e: udtE)
System.out.println(e.key);
}
}
class Element{
public int key;
}
--
╭──── Origin:<不良牛牧場> bbs.badcow.com.tw (210.200.247.200)─────╮
│ ↘ Welcome to SimFarm BBS -- From : [59.116.179.14] │
╰◣◣◢ ◢◢《不良牛免費撥接→電話:40586000→帳號:zoo→密碼:zoo》 ◣◣◢ ─╯
java 近期熱門文章
PTT數位生活區 即時熱門文章