首页 > 解决方案 > 使用用户输入创建多个相同类型的对象?

问题描述

我正在尝试制作一个包含三个类文件、两个对象文件和一个 Main 的程序,它可以访问两者并运行操作。例如,第一对象文件使用一个参数创建对象,然后根据所述参数为其自身分配属性。

public class People {
    private int height, weight;
    private String specificPerson;
    public People(String  person){
        this.specificPerson = person;
        this.height = person.length * 12;
        this.weight = person.length * 40;
    }

    public int getHeight(){return height;}

    public int getWeight() {return weight;}
}

然后将这些对象存储在另一个具有容量和数组的对象的数组中:

public class peopleIndexer {
    private int pcapacity, size;
    private String[] peopleArray;        
    public peopleIndexer(int capacity){
        this.pcapacity = capacity;
        this.peopleArray = new String [capacity];
    }

    public int getCapacity(){
        return pcapacity;
    }

    public int[] getInfo(String person){
        int[] getInfo = new int[2];
        int found = Arrays.binarySearch(peopleArray,person);
        getInfo[0] = ?.getHeight();
        getInfo[1] = ?.getWeight();//I dont know the object name yet so I put "?" for I am not sure
        System.out.println("Person" + person + "is " + getInfo[0] + "tall and " + getInfo[1] + " pounds.");
    }

}

我需要知道的是如何允许用户使用输入在列表中创建多个人,然后我可以允许他们稍后检索,例如:

String user_input;
People user_input = new People("user_input");

因此,如果用户输入是 jack、ryan 和 nick,我将在 peopleIndexer 中放置三个对象,如下所示:

People jack = new People(jack);
People ryan = new People(ryan);
People nick = new People(nick);

标签: javaclassoopobjectinheritance

解决方案


您的 People 构造函数只接受一个参数并创建一个 People 对象。您在 peopleIndexer 类中没有一些私有变量的设置器,因此最好将您的 main 方法作为 peopleIndexer 类的一部分。

People 构造函数中的“长度”属性未在任何地方初始化或声明,因此我们假设它不存在。你必须改变你的“私人字符串[] peopleArray;” 成为“私人人 [] peopleArray;” 为了让人在阵中。

public static void main(String args[]){
    
    Scanner input = new Scanner(System.in);
    int capacity;
    int peopleCount = 0; //used to keep track of people we have in our array
    String person = "";
    
    // get the capacity from the user
    System.out.println("Enter the number of people you want to capture: ");
    capacity = Integer.parseInt(input.nextLine());
    
    //create peopleIndexer object using the given capacity
    peopleIndexer pIndexer = new peopleIndexer(capacity); 

    while(peopleCount < capacity){

          //prompt the user for the "People" name, this is the only attibute we need according to your constructor.
          System.out.println("Enter person "+(peopleCount + 1)+" name: ");
          person = input.nextLine();
          
          //add a new person into the array
          peopleArray[peopleCount] = new People(person);

          //increase the number of people captured
          peopleCount += 1;
    }
} 

推荐阅读