抱歉,这可能是重复的,我不确定我之前发布的尝试是否通过了。
几周前开始学习 Java,完成了我的第一个任务。:)
我的问题有些基本,但是在查看了以前解决的主题后,我找不到它的完全等价物。这不是现实生活中的问题,所以我想我希望以非常具体的方式解决它。
所以这个任务包括几个步骤——我必须创建一个包含许多自定义对象的超类,添加新的子类,实现新的方法来计算某些变量的值,编写测试类并对我的输出进行排序。
除了最后一步之外,这一切都已完成。不确定我是否可以在网上发布类似的问题,但这是我现在所处的位置:
我有类似的东西:
public class Pants
{
public enum SizeType {SMALL, MEDIUM, LARGE, EXTRA_LARGE}
private SizeType size;
private String brand;
private String countryOfOrigin;
private String color;
private double price;
//Other variables and methods
}
public class Jeans extends Pants
{
//new variables and methods
}
public class Shorts extends Pants
{
//some more new variables and methods
}
和其他类似的子类。
import java.util.ArrayList;
public class Selection
{
public static void main(String[] args){
Jeans ex1 = new Jeans("John Lewis");
ex1.countryOfOrigin("US");
ex1.color("Navy");
ex1.setSize(Pants.SizeType.LARGE);
ex1.setprice(40);
ex1.machineWashable(true);
System.out.println(ex1);
Shorts ex2 = new Shorts("Ted Baker");
ex2.countryOfOrigin("United Kingdom");
ex2.color("White");
ex2.setSize(Pants.SizeType.MEDIUM);
ex2.setprice(30);
ex2.machineWashable(true);
System.out.println(ex2);
//..etc
ArrayList<Pants> selection = new ArrayList<Pants>();
selection.add(ex1);
selection.add(ex2);
selection.add(ex3);
selection.add(ex4);
selection.add(ex5);
System.out.println( "Size - LARGE: " );
System.out.println();
Pants.SizeType size;
size = Pants.SizeType.LARGE;
ListPants(selection,size);
我需要编写一个 ListPants 方法来根据 SizeType 列出对象 - 在这种情况下从 large 开始。我不认为我可以实现任何额外的接口(这是其他线程中最推荐的)。
请在下面查看我的尝试(无效)。我在这里思考的方向是正确的,还是?
public static void ListPants(ArrayList<Pants> selection, Pants.SizeType size)
{
for (Pants.SizeType sizeType : Pants.SizeType.values()) {
for (Pants pants : selection) {
if (pants.getSize().equals(sizeType)) {
System.out.println(selection.toString());