我試圖從HockeyPlayer構造函數獲取用戶輸入的HockeyPlayer類在數組「玩家」我HockeyPlayerMain類的陣列來存儲。每當他們按「A」它將調用構造函數,如果他們輸入數字#6,我需要將對象/實例放入數組索引#5,但我不知道如何做到這一點,非常初學數組。把用戶輸入的某一點在數組索引
對不起,如果這不明確,但我可以嘗試清除事情。
package hockeyplayer;
import java.util.Scanner;
public class HockeyPlayer {
private String[] opponent = new String[10];
private int[] goalsScored = new int[10];
private int[] gameNumber = new int[10];
private String name;
private int playerNumber;
private int gameNum;
public HockeyPlayer() {
Scanner input = new Scanner(System.in);
System.out.println("What is the name of the player?");
name = input.nextLine();
System.out.println("What is the player's number?");
playerNumber = input.nextInt();
input.nextLine();
}
public String[] getOpponent() {
return opponent;
}
public void setOpponent(String[] opponent) {
this.opponent = opponent;
}
public int[] getGoalsScored() {
return goalsScored;
}
public void setGoalsScored(int[] goalsScored) {
this.goalsScored = goalsScored;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPlayerNumber() {
return playerNumber;
}
public void setPlayerNumber(int playerNumber) {
this.playerNumber = playerNumber;
}
public void addGameDetails(){
HockeyPlayer player1 = new HockeyPlayer();
Scanner input = new Scanner(System.in);
System.out.println("What game number was it?");
gameNumber[0] = input.nextInt();
input.nextLine();
System.out.println("Who were the opponents?");
opponent[0] = input.nextLine();
System.out.println("How many goals did the player score?");
goalsScored[0] = input.nextInt();
}
}
package hockeyplayer;
import java.util.Scanner;
public class HockeyMain {
private static String choice;
private static HockeyPlayer[] players = new HockeyPlayer[12];
private static final String MENU = "Hockey Tracker\n"+
"A-Add Player\n"+
"G-Add game details\n"+
"S-Show players\n"+
"X-Quit\n";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do{
System.out.println(MENU);
choice = input.nextLine();
switch(choice){
case "A":
for(int i = 0; i < players.length; ++i){
players[i] = new HockeyPlayer();
}
break;
case "G":
break;
case "S":
break;
case "X":
}
}while(!choice.equals("X"));
}
}
您的意思是'HockerPlayer'構造函數中給出的數字應該是'HockeyMain'類中數組播放器的索引嗎? – nikowis
順便說一句,整個邏輯看起來很「奇怪」,但@Maciej Kowalski的回答是正確的。 – Vadim