在不使用java.util的情况下,将对象数组排序为堆栈



我必须通过随机生成50人的年龄和ID来创建一个对象数组。之后,我必须将列表中生成的每个人分类为2个堆栈数组,其中第一个堆栈将包含年龄低于18岁的人,第二个堆栈将包括年龄超过18岁的人员。人员的分类,包括删除初始列表中的每个元素并将它们插入相应的堆栈,必须是一个自动执行的过程。我已经完成了第一部分,但我在分类方面遇到了问题,因为我不能使用java.util来创建堆栈。如果你能帮我做这件事,我将不胜感激。

public class Stacks01 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//create array of employee object  
Person[] person = new Person[50] ;
Person[] minors = new Person[50];
Person[] adults = new Person[50];

for (int i = 0; i < 50; i++)
{
person[i] = new Person (generatorId(100000000, 999999999), generatorAge(0,100));
}

for (int j = 0; j < 50; j++)
{
System.out.println("Person "+(j+1)+": ");
person[j].showData();

}

}
//Person class with Id and age as attributes
static class Person{
int Id;
int age;
//Person class constructor
Person(int pId, int e){
Id = pId;
age = e;
}

public void showData(){
System.out.print("Id: "+Id + "  " + " age: "+age);
System.out.println();
}
}

public static int generatorId(int min, int max){
double id;
id = ((Math.random() * (max - min)) + min); 
return (int) id; 
} 
public static int generatorAge(int min, int max){
double age;
age = ((Math.random() * (max - min)) + min); 
return (int) age; 
} 

只需遍历person数组,并为索引保留两个计数器。

for(int i=0, a=0, m=0; i < person.length; i++){
var aux = person[i];
if(aux.age < 18) minors[m++] = aux;
else adults[a++] = aux;
}

在我的建议中,a是一个计数器,它为检测到的每个成年人递增;并且对于检测到的每一个子帧增加m个增量。

此外,我建议删除Person.showData,相反,您可以覆盖到String,然后只需调用System.out.println(person[i]);

此外,您可以使用java.util.random,而不是使用Math.random,它有更好的方法(nextInt、nextLong,甚至可以生成随机数流(。我会用的。

最新更新