Java:如何在静态方法中创建对象并从另一个类调用方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10236792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:09:44  来源:igfitidea点击:

Java: How do i create objects in a static method and also call for methods from another class?

javaclassobjectmethodsstatic

提问by Panda

I am doing this Java assignment for hours and stuck with this tester class for very almost 5 hours.

我做了几个小时的 Java 作业,并在这个测试类课程中坚持了将近 5 个小时。

In this assignment, I have created a Product class, a Money class, a LineItem class and an Inventory class. Now i need to create a test class to test the program by putting new lineitems into the inventory array.

在这个作业中,我创建了一个 Product 类、一个 Money 类、一个 LineItem 类和一个 Inventory 类。现在我需要创建一个测试类来通过将新的 lineitems 放入库存数组来测试程序。

In the tester class, I am trying to create a static method public static void addTestItems(Inventory theInventory)which suppose to add 4 items. For each item I will need to create a product object followed by a LineItem object to contain the newly created product. next i need to use a method from the inventory class to add the items into the array in the inventory class.

在测试类中,我试图创建一个静态方法public static void addTestItems(Inventory theInventory),假设添加 4 个项目。对于每个项目,我需要创建一个产品对象,然后是一个 LineItem 对象以包含新创建的产品。接下来我需要使用库存类中的方法将项目添加到库存类中的数组中。

What i have tried too so far:

到目前为止我已经尝试过什么:

private static void addTestItems(Inventory theInventory)
{
    Inventory[] _items;
    Product product1 = new Product("Book","Objects first with Java"," An excellent introductory Java textbook");
    Product product2 = new Product("CD","The dark side of the moon","The all-time classic Pink Floyd album");
    Product product3 = new Product("DVD", "Transformers","Robots in disguise");
    Product product4 = new Product("Laptop","Lenovo T42","A good yet affordabble laptop");
    Money unitPrice1 = new Money(29,99);
    Money unitPrice2 = new Money(4,99);
    Money unitPrice3 = new Money(9,99);
    Money unitPrice4 = new Money(450,0);
    _items[0] = new LineItem(product1,5,unitPrice1);
    _items[1] = new LineItem(product2,8,unitPrice2);
    _items[2] = new LineItem(product3,200,unitPrice3);
    _items[3] = new LineItem(product4,9,unitPrice4); 
}

The current error is incompatible types- found LineItem but expected Inventoryso i tried changing Inventory[] _items;to LineItem[] _items;. But the error was variable _items may not be initialise.

当前的错误是incompatible types- found LineItem but expected Inventory所以我尝试更改Inventory[] _items;LineItem[] _items;. 但错误是变量 _items 可能未初始化。

Sorry guys I am a real noob in Java, I tried searching on-line for ages but I do not quite understand most results. The only one i understand was http://forums.devshed.com/java-help-9/bluej-compiler-error-cannot-find-symbol-variable-object-688573.htmlbut i tired putting into my context but failed. I also found lot of results but they had constructors and instance variables in them which my teacher specifically mentioned that I will not need them.

对不起,我是 Java 的真正菜鸟,我尝试在网上搜索了很长时间,但我不太明白大多数结果。我唯一理解的是http://forums.devshed.com/java-help-9/bluej-compiler-error-cannot-find-symbol-variable-object-688573.html但我厌倦了放入我的上下文但失败了. 我还发现了很多结果,但它们中有构造函数和实例变量,我的老师特别提到我不需要它们。

Wonder if expert could guide me along like let me know my mistakes. Thanks thanks.

想知道专家是否可以指导我,让我知道我的错误。谢谢,谢谢。

The inventory class:

库存类:

/**
* In the Inventory class, it is merely to create a list / array of product which allows    the information from the linitem to be put with an index.
* For example, for the first product, we can use the inventory class to input it into the index 1. and he next product into index 2 and so on.
 * It is suse to create an array and inputing the lineitem information into it.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
 public class Inventory
{
// instance variables - replace the example below with your own
private LineItem[] _items;
private int _numItems;


/**
 * Constructor for objects of class Inventory
 */
public Inventory()
{
    // initialise instance variables
    _items = new LineItem[1000];
    _numItems = 0;
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void addItem(LineItem item)
{
   _items[_numItems]= item;
   _numItems++;
}

public String toString()
{
    String result="";
    int i=0;
    while (i < _numItems)
    {
        result = result + _items[i] + "/n";
        i++;
    }
    return result;
}

public void print()
{
    String myResult=this.toString();
    System.out.println(myResult);
}

public Money getTotalValue()
{
    int i=0;
    Money total= new Money(0);
    while (i<_items.length)
    {
        total = total.add(Money.NO_MONEY);
        i++;
    }
    return total;
}

public LineItem getItem(String productName)
{
    int i = 0;
    LineItem itemDetails = null;
    while (i<_items.length)
    {
        if (_items[i].equals(productName))
        {
            itemDetails= _items[i];
        }
        else
        {
            //do nothing
        }
        i++;
    }
    return itemDetails;
   }
}

I have yet to comment on the methods yet but will do so once i understand it.

我还没有对这些方法发表评论,但一旦我理解它就会这样做。

回答by Jon Skeet

Your arrayis of type Inventory[]- but you're trying to assign references of type LineItem. You're alsonot initializing it. Change this:

您的数组属于类型Inventory[]- 但您正在尝试分配类型的引用LineItem。你没有初始化它。改变这个:

Inventory[] _items;

to this:

对此:

LineItem[] _items = new LineItem[5];

And all should be well - although you're not using index 0 (which is why you need it to be size 5) and you're not doing anything with the array afterwards either...

一切都应该很好 - 虽然你没有使用索引 0(这就是为什么你需要它的大小为 5)并且之后你也没有对数组做任何事情......

Another alternative to using an array is to use a List:

使用数组的另一种替代方法是使用列表:

List<LineItem> items = new ArrayList<LineItem>();
items.add(new LineItem(product1, 5, unitPrice1));
items.add(new LineItem(product2, 8, unitPrice2));
items.add(new LineItem(product3, 200, unitPrice3));
items.add(new LineItem(product4, 9, unitPrice4));

... next think about what you actually want to dowith the itemsvariable.

...接下来想想你真正想用这个变量什么items

回答by bernabas

LineItem[] _items = new LineItem[4];

then the index starts from 0 not from 1,

然后索引从 0 开始,而不是从 1 开始,

_items[4] 

will return indexoutofbounds error

将返回 indexoutofbounds 错误

回答by Michael

A few things:

一些东西:

incompatible types- found LineItem but expected Inventory

is caused by the fact that your array is supposed to contain Inventory objects but you're assigning LineItems to it instead

是因为您的数组应该包含 Inventory 对象,但您将 LineItems 分配给它

variable _items may not be initialise

means that you have your _items object but you haven't initialized it to anything. You want to do

意味着您拥有 _items 对象,但尚未将其初始化为任何内容。你想做

LineItem[] _items = new LineItem[4];

PS: If you want dynamically sized arrays, don't know how many line items you'll potentially load, etc etc use a vector or a collection or something along those lines.

PS:如果你想要动态大小的数组,不知道你可能会加载多少行项目,等等使用向量或集合或这些行的东西。

Also,

还,

_items[1] = new LineItem(product1,5,unitPrice1);
_items[2] = new LineItem(product2,8,unitPrice2);
_items[3] = new LineItem(product3,200,unitPrice3);
_items[4] = new LineItem(product4,9,unitPrice4); 

In Java, array elements start with index 0 and not 1

在 Java 中,数组元素以索引 0 而不是 1 开始

_items

is a wonky variable name that makes your team mates sneeze in your coffee

是一个奇怪的变量名,它会让你的队友在你的咖啡里打喷嚏