使用用户输入创建多个相同类型的对象?

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

search.php

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

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.");
    }

}

因此,如果用户输入的是杰克,瑞恩和尼克,我将在personIndexer中放置三个对象,如下所示:

String user_input;
People user_input = new People("user_input");
g6228560 回答:使用用户输入创建多个相同类型的对象?

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

People 构造函数中的“长度”属性未在任何地方初始化或声明,因此我们假设它不存在。你必须改变你的“private String[] peopleArray;”成为“私人 People[] 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;
    }
} 
本文链接:https://www.f2er.com/3135591.html

大家都在问