2

抱歉,这可能是重复的,我不确定我之前发布的尝试是否通过了。

几周前开始学习 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());    
4

2 回答 2

1

我认为这只是你面临的一个小问题。您已经定义了应该打印出特定尺寸的所有裤子的方法的签名:

ListPants(ArrayList<Pants> selection, Pants.SizeType size)

那是对的。现在,您的代码正在遍历所有裤子和所有可能的尺寸:

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()); 

由于这看起来像是一项家庭作业,我将把我的答案表述为一个问题:

你在哪里使用size方法体中的参数ListPants

于 2012-12-08T23:56:30.210 回答
0

我假设您的类无法实现新接口,并且根本不使用接口。

您可以使用为您的班级构建的Collections.sort(List,Comparator)a 。Comparator

就像是

Collections.sort(selection,new Comparator<Pants>() { 

   @Override
   public int compare(Pants p1, Pants p2) { 
       //implement your compare method in here
       ...
   }
});

如果您渴望创建自己的排序算法,请查看此排序算法列表。最简单的实现(虽然很慢)IMO 是选择排序

于 2012-12-08T23:46:54.957 回答