2014-01-07 86 views
1

我是Java的新手,遇到了這個問題:我正在學習如何將對象狀態保存到文件中,並且我將數組傳遞給了構造函數。我相信問題是構造函數的基類,但我不確定。Java將一個數組傳遞給構造函數

這裏是我的英雄職業:

import java.io.Serializable; 


public class Hero implements Serializable{ 

/** 
* 
*/ 
private static final long serialVersionUID = 1L; 

private int power; 
private String type; 
private String[] wepons; 


public int getPower() { 
    return power; 
} 


public void setPower(int power) { 
    this.power = power; 
} 


public String getType() { 
    return type; 
} 


public void setType(String type) { 
    this.type = type; 
} 


public String[] getWepons() { 
    return wepons; 
} 


public void setWepons(String[] wepons) { 
    this.wepons = wepons; 
} 

public Hero(int powerH, String typeH, String[] weponsH) { 
    this.power = powerH; 
    this.type = typeH; 
    this.wepons = weponsH; 
} 

} 

,這裏是一流的,我試着用它來保存對象狀態:

import java.io.*; 
public class SaveGame { 

public static void main(String[] args) { 

    Hero hero1 = new Hero(50, "Elf", new String[] {"bow", "short sword", "powder"}); 


    try{ 
     ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Game.ser")); 
     os.writeObject(hero1); 
     os.close(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 

    ObjectInputStream is; 

    try { 
     is = new ObjectInputStream(new FileInputStream("Game.ser")); 
     Hero p1N = (Hero) is.readObject(); 
     System.out.println(p1N.getPower() + " " + p1N.getType() + " " + p1N.getWepons()); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
} 

} 

你能告訴我,說明我在做什麼錯。我真的需要在我的英雄班中使用setter和getters,並且我有這種感覺,我錯誤地使用了它們。

我的問題是,當我試圖打印出英雄的參數時,我得到了數組的內容而不是數組的字符串表示。感謝user2336315我現在知道我應該在打印一個數組的內容時使用Arrays.toString方法

+2

究竟發生了什麼?你有編譯錯誤嗎?例外?有什麼行爲與你的期望有所不同? – user2357112

+3

沒有相關性,但是你寫了'wepons'錯誤 –

+0

_「我真的需要在我的Hero類中使用setter和getter,並且我有這種感覺,我錯誤地使用它們。」 - 帶有getter和setter的private字段是良好的做法。你似乎正在使用它們。 –

回答

5

我運行了你的代碼,一切似乎都很好。唯一的問題是你想打印數組本身的內容,而不是數組本身的字符串表示。因此,使用Arrays.toString

System.out.println(p1N.getPower() + " " + p1N.getType() + " " + Arrays.toString(p1N.getWepons())); 

輸出:

50 Elf [bow, short sword, powder] 
+0

+1良好的捕獲,這可能是爲什麼OP認爲他們沒有正確使用吸氣劑 –

+0

Arrays.toString ...很高興知道! –

+0

謝謝!這是我的錯,我沒有說出問題到底是什麼。正如你所說的,當我試圖打印出來時,它給了我數組的內容而不是數組的字符串表示。再次感謝! – Lenny

0

反序列化機制創建使用它的元數據的類。它不依賴於目標類成員的訪問級別,包含構造函數。 (你的代碼甚至可以工作,即使英雄類有私人默認構造函數。)