我如何创建用户填充的对象数组并查看数组元素?

时间:2019-04-28 20:09:02

标签: java arrays

我创建了一个方法来创建将由用户填充的对象数组,并创建了另一个方法来显示填充的数组。我在查看数组时遇到问题,无法弄清楚出了什么问题。

public void addPlayer() {
    for (int i = 0; i < 11; i++) {
        System.out.println("player  " + (i + 1));
        System.out.println("Name:");
        String name = scan.next();
        System.out.println("Sweater number:");
        int sNr = scan.nextInt();
        System.out.println("Card (red,null,yellow)");
        String card = scan.next();
        players[i]=new Player(name,sNr,card);
    }
}

1 个答案:

答案 0 :(得分:1)

您还可以使用单独的Player pojo类和设置器,设置器来设置和获取数据。

package com.testapp.main;

    import java.util.Scanner;

    public class Player {
        private String name;
        private int sNr;
        private String card;

        public Player() {

        }

        public Player(String name, int sNr, String card) {
            this.name = name;
            this.sNr = sNr;
            this.card = card;
        }


        @Override
        public String toString() {
            return "Player [name=" + name + ", sNr=" + sNr + ", card=" + card + "]";
        }

        public void addPlayer() {
            Scanner scan = new Scanner(System.in);
            Player players[] = new Player[10];
            for (int i = 0; i < 11; i++) {
                System.out.println("player  " + (i + 1));
                System.out.println("Name:");
                name = scan.next();
                System.out.println("Sweater number:");
                sNr = scan.nextInt();
                System.out.println("Card (red,null,yellow)");
                card = scan.next();
                players[i] = new Player(name, sNr, card);
                System.out.println(players[i]);
            }
        }

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Player p = new Player();
            p.addPlayer();
        }

    }