访问对象数组-Java

时间:2015-10-10 14:42:42

标签: java oop

public static void getCount()
{
    System.out.println("How Many Players? ");
    int a = inputCount.nextInt();
    while(a <2 || a > 8)
    {
        System.out.println("How Many Players? ");
        a = inputCount.nextInt();
    }
    count = a;
}

public static void addPlayers(int count)
{ 

    Object[] playerStats = null;
    for (int i = 1;i <= count; i++)
    {

        System.out.println("Enter Name: ");
        String a = inputName.nextLine();
        name = a;
        int balance = 1500;
        int positon = 0;
        playerStats = new Object[]{i, name, balance, positon};
    }
}

在这种情况下,我想从用户输入创建一个玩家名称,然后我想要添加这个名称以及平衡和定位到一个对象。

我的问题是我不完全确定我将如何在for循环之外访问此对象并在唯一的基础上使用它们,因为一次只能创建多个名称。

谢谢,请保持温柔,我对此非常陌生。

编辑:感谢回复的人,我会尝试这些想法。

2 个答案:

答案 0 :(得分:2)

创建一个Player类来存储您需要的统计数据,例如:

class Player {
    private final String name;
    private final int balance;
    private final int position;

    public Player(String name, int balance, int position) {
        this.name = name;
        this.balance = balance;
        this.position = position;
    }
}

然后我推荐另一个类来处理用户输入,并创建一个播放器列表,例如:

class PlayerInput {

    private final Scanner scanner;

    PlayerInput(Scanner scanner) {
        this.scanner = scanner;
    }

    public int getCount() {
        int count;
        do {
            System.out.println("How Many Players? ");
            count = scanner.nextInt();
        } while (count < 2 || count > 8);
        return count;
    }

    public List<Player> inputPlayers(int count) {
        List<Player> players = new ArrayList<>();
        for (int i = 1; i <= count; i++) {
            System.out.println("Enter Name: ");
            String name = scanner.nextLine();
            int balance = 1500;
            int position = 0;
            players.add(new Player(name, balance, position));
        }
        return players;
    }
}

您可以使用这些类,例如:

public class App {
    public static void main(String[] args) {
        PlayerInput input = new PlayerInput(new Scanner(System.in));
        int count = input.getCount();
        List<Player> players = input.inputPlayers(count);
    }
}

答案 1 :(得分:0)

Object[] playerStats = new Object[count];
    for (int i = 1;i <= count; i++)
    {

        System.out.println("Enter Name: ");
        String a = inputName.nextLine();
        name = a;
        int balance = 1500;
        int positon = 0;
        playerStats[i] = new Object(i, name, balance, positon);
    }

这是你在拥有不同对象数组时应该做的事情。为了访问,让我们说,数组的索引1的名称:

playerStats[i].getName();

但请注意,您的数组只能在您的方法中访问。

为什么不将返回类型更改为Object[]并返回创建的数组。像这样,它可以在任何其他地方访问。