Java从单独的类调用方法来指定存储哪些对象数据?

时间:2014-05-09 01:59:22

标签: java class methods

我应该先说一下我对java和编程相对较新。我已经搜索了一些与此有关的答案,但似乎没有人回答我的问题。我能找到的最接近的答案是:java calling a method from another class。这个答案没有帮助的原因是因为我已经知道需要初始化一个实例来从一个单独的类调用一个方法。我遇到的问题是,如何调用方法来指定我想从哪个对象读取数据?

我现在的代码是。接口类的方法:

private void writeOutput()
//The user enters the name of a product, if the product doesn't exist, 
//the user is prompted to enter a product that does exist
//Then displays the data stored for said product
{             
    String productName;
    System.out.println("Please enter a product: ");
    productName = console.next();
    matesStore.isAProduct(productName);  //Checks whether the product exists
    while (!matesStore.isAProduct(productName))
    //If the product doesn't exist, the user must enter a valid product
    {
        System.out.println("That is not a valid product.\n" + "Please choose a product: ");
        productName = console.next();
    }
    while (matesStore.isAProduct(productName))
    {
        System.out.println("The records of " +productName+ " are:");
        System.out.println("Demand rate: "+matesStore.readDemand(productName));
        System.out.println("Setup Cost: "+matesStore.readSetup(productName));
        System.out.println("Unit Cost: "+matesStore.readUnit(productName));
        System.out.println("Inventory Cost: "+matesStore.readInventory(productName));
        System.out.println("Selling Price: "+matesStore.readPrice(productName));
    }
    continueOption();
}

Store类的一种读取方法:

public String readDemand(String nameOfProduct)
{
    String productDemandRate;
    productDemandRate = product1.getDemand() + "."; 
    //!!!!This line is the problem. product1 is here just so I could 
    //test that the method actually works



    return productDemandRate;       
}

来自Product类的访问器方法:

public String getName()
{
    return name;        
}

所以我的问题是如何在行productDemandRate = product1.getDemand() + ".";中替换product1以便显示正确的数据?

很抱歉,如果我的问题有点模糊,或者甚至可能非常明显。在过去的几个小时里,我一直在努力解决这个问题而没有运气。所以任何帮助或建议将不胜感激。

干杯:)

P.S这适用于大学项目,如果您不知道我为什么不使用数组,则严格禁止使用数组。

1 个答案:

答案 0 :(得分:0)

您有一个Product类,它允许您创建Product个对象来保存您在此处尝试使用的数据。然后,你可以简单地改变你的方法:

public String readDemand(Product product1){
  ...
}

不使用输入中的产品名称,而是创建一个Product,其name属性包含产品名称。将产品传递给方法,以便您可以按照自己的方式使用它们。