有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java使用来自另一个类的数组

我是Java新手,所以请温柔一点

考虑以下^ ^ {CD1>}:

public class ShoppingList {
...
    public ItemPrices[] getSortedPrices(){
        //do sorting stuff here etc
        return ret.toArray(new ItemPrices[0]);
    }
}

现在我有了另一个叫做Hello的类:

public class Hello {
...
    private Groceries createGroceries() {
    ...
         pricearray[] =  ShoppingList.ItemPrices[] //????
    ...
    }
}

我想将我创建的数组pricearray指定为等于方法中返回的ItemPrices数组

但是我没有得到我想要的,正确的方法是什么


共 (2) 个答案

  1. # 1 楼答案

    在不关注其他问题的情况下,你必须做以下事情

    ShoppingList sl = new ShoppingList();
    ItemPrices[] pricearray =  sl.getSortedPrices();
    

    但这需要你知道类型、构造函数、数组、如何调用一个方法以及其他很多事情

  2. # 2 楼答案

    除非方法getSortedPrices是一个静态方法,否则需要从ShoppingList类的实例中调用它,因此应该按如下方式创建一个实例

    public class Hello {
    ...
        private Groceries createGroceries() {
        ...
            ShoppingList sList = new ShoppingList();
            PriceList [] pricearray =  sList.getSortedPrices() //you call a method by its name, not return type.
        ...
        }
    }
    

    而且,我不明白怎么做

    (ItemPrices[] is a double).

    它应该是一个double数组,还是一个ItemPrices类实例数组? 如果它应该是一个双倍数组,你需要这样做:

    public class ShoppingList {
    ...
        public double[] getSortedPrices(){
            //do sorting stuff here etc
            return new double[n] // n is the length of the array
        }
    }
    

    线路呢

    PriceList [] pricearray = sList.getSortedPrices()

    应该是

    double [] pricearray = sList.getSortedPrices()