import java.util.ArrayList;
import java.util.Scanner;
public class SmallPet
{
private String name, ans;
private int age;
private double weight;
ArrayList<Pet>petList = new ArrayList<Pet>(1);
Scanner keyboard = new Scanner(System.in);
public void newPet()
{
do
{
System.out.println("Enter the Name of the Pet:");
name = keyboard.nextLine();
Boolean validAge=true;
do
{
System.out.println("Enter the Age of the Pet:");
age = keyboard.nextInt();
keyboard.nextLine();
if (age==(int)age)
{
System.out.println("Invalid, please enter a correct age.");
validAge = false;
}
else if (age<=0)
{
System.out.println("Invalid, please enter a correct age.");
validAge = false;
}
}while(!validAge);
Boolean validWeight=true;
do
{
System.out.println("Enter the Weight of the Pet:");
weight = keyboard.nextDouble();
keyboard.nextLine();
if (weight==(int)weight)
{
System.out.println("Invalid, please enter a correct weight.");
validWeight = false;
}
else if (weight<=0)
{
System.out.println("Invalid, please enter a correct weight.");
validWeight = false;
}
}while(!validWeight);
System.out.println("Again? Yes or No?");
ans = keyboard.next();
} while (ans.equalsIgnoreCase("yes"));
typeToArray()
{
}
}
我似乎不知道如何将这些宠物对象添加到数组中,然后按重量从最小到最大的顺序对其进行排序。这是我面临的问题。
对宠物重量排序,而不要按名称排序。在屏幕上显示排序的数据后,写下5磅以下的宠物的数量和百分比,5到10磅的宠物的数量和百分比,以及10磅以上的宠物的数量和百分比。
最佳答案
要将某些内容添加到ArrayList
,请使用.add()
函数。
要按重量排序,您需要覆盖默认的compare()
函数。然后,调用Collections.sort()
并将ArrayList
作为参数放入sort函数。请注意,您的Pet
类应实现Comparable
。
关于java - 需要有关如何将宠物对象放入数组的帮助吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29905030/