2015-10-05 105 views
0

http://pastebin.com/xBqdUtTg操作數組(和一般的變量) - 主要 http://pastebin.com/BadasC7N - 構造如何instantiante並在構造函數類

我要創建程序增加了一個球員到一個數組構造文件的方法,但我不允許更改上述項目中給出的代碼片段。我的問題是,我不知道如何通過用戶輸入實例化具有正確大小的數組,因爲我必須堅持使用addAPlayer(String playername)的框架,並且不能添加參數來決定長度。此外,我不知道如何操縱變量在構造函數中

public class Practice{ 
    public Practice(){ 
     int x; 
     int y; 
    } 
    public static void main(String[] args){ 
     Practice prac = new Practice(); 
     prac.x = 1; 
     prac.y = 2; 
    } 
} 

不工作,所以其他什麼我是不可能操縱這些變量?在我被授予作業的存根代碼中有類變量,但它們被標記爲私有的,所以我不能直接更改它們,並且已經給出了構造函數的參數,所以我無法在其中定義它們

編輯:在主文件中也是for循環每次調用addAPlayer方法以設置通過用戶輸入輸入的正確數量的玩家名稱,但我怎樣才能確保每次調用該方法時它設置等於名稱

編輯不同的索引的數組:

public class NBATeam { 
    private String sTeamName; 
    private int nWin; 
    private int nLoss; 
    private String [] playerArray; 
    //Your code here 

    }//end of class definition 

^^^構造

//Warning: Do not change the given codes 
import java.util.Scanner; 

public class NBA { 
    public static void main(String[] args) { 

      //construct Team Heat 
      NBATeam heat= new NBATeam("Heats"); 
      System.out.print("How many players Heats own: "); 
      Scanner input = new Scanner (System.in); 
      int numberOfPlayers = input.nextInt(); 

      // Prompt user to enter players into the Team 
      for (int i = 0; i < numberOfPlayers; i++) { 
        System.out.print("Enter the name of Player #" + (i + 1) + ": "); 
        String playerName = input.next(); 
        heat.addAPlayer(playerName); 
      } 

      //construct Team Spurs 


      //Your code here 
+1

請將相關代碼複製到您的問題中,而不是提供pastebin鏈接。 –

+0

您的發佈代碼顯示在構造函數中創建局部變量,這看起來不像您想要的。 –

+0

你去了,不知道爲什麼每個人都不喜歡pastebin鏈接,儘管 –

回答

0

除非您知道要添加多少玩家,否則不要創建NBA團隊的實例。這一切都假設你不能使用列表<>。

on line 12: 
NBATeam heat= new NBATeam("Heats", numberOfPlayers); 

然後,在類NBATeam補充:

int currentIndex; 
public NBATeam(String name, int numberOfPlayers) { 
    sTeamName = name; 
    playerArray = new String[numberOfPlayers]; 
} 
public void addAPlayer(String playerName) { 
    playerArray[currentIndex] = playerName; 
    currentIndex++; 
} 

再次,這是所有有點容易出錯,你應該檢查一下addAPlayer調用過於頻繁。您還需要佔playerArray沒有完全填滿等 您還需要檢查是否傳遞到構造函數numberOfPlayers是有效值等

最好使用該列表<>,但因爲你必須使用示例代碼中的數組,您必須添加所有這些檢查(作爲練習留給讀者)

+0

問題在於,我受到教授給我的參數限制。我只允許在構造函數中使用1個參數,如果這裏的教訓是要了解數組,並且它們不僅僅是擴展了長度,那麼您基本上需要爲每個數組重新分配playerArray,並且該參數是名稱 –

+0

調用addAPlayer,將舊陣列複製到新陣列並添加新玩家。 這是醜陋的地獄和浪費。 –

+0

以及如何在構造函數中從構造函數 –