2011-12-07 18 views
0

我在這裏有一些小問題。在不創建類的新實例的情況下更改「文件」參數的值

我在這些方法中,宣佈了新的對象「艦隊」:

public void run() throws FileNotFoundException 
{ 
    File file = new File(getFile()); 
    Fleet fleet = new Fleet(file); 
    buildFleet(file, fleet); 
    } 

private void buildFleet(File file, Fleet fleet) throws FileNotFoundException 
{ 
    fleet.addVehicle(Honda); 
    userMenu(fleet); 

} 

最後一行調用userMenu的()方法。在這種方法中,我需要能夠更改Fleet中的「File」的值,而無需創建類的新實例。

private void userMenu(Fleet fleet) throws FileNotFoundException 
{ 
    PrintWriter pw = new PrintWriter("temp.txt"); 
    File file = new File("temp.txt"); 
    fleet = new Fleet(file); 

    this.createMenu(); 
    choice = this.menu.getChoice(); 


while(choice != 8) 
{ 
    switch(choice) 
    { 
    case 1: 
     //Do stuff 
     fleet.addVehicle(Honda); 
     break; 
    } 
} 

此外,我不允許創建任何新的班級數據。 有什麼建議嗎?

回答

0

解決改變你的艦隊對象內部文件:

我改變了:

private void userMenu() throws FileNotFoundException 
{ 
    PrintWriter pw = new PrintWriter("temp.txt"); 
    File file = new File("temp.txt"); 

至:

private void userMenu(Fleet fleet) throws FileNotFoundException 
{ 
    PrintWriter pw = new PrintWriter("temp.txt"); 
    File file = new File("temp.txt"); 
    fleet.file = file; 
1

什麼對你Fleet類二傳手的文件:

public class Fleet { 
    private File file; 
    ... 

    public void setFile(File file){ 
    this.file = file; 
    } 
} 

然後,您可以調用此方法通過調用

fleet.setFile(myNewFile); 
相關問題