Java从一个单独的类中调用一个方法来指定存储在哪个对象数据中?
首先,我要说的是,我对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,以便它显示正确的数据
抱歉,如果我的问题有点模糊,或者甚至是盲目的明显。在过去的几个小时里,我一直在努力独自解决这个问题,但运气不佳。因此,任何帮助或建议都将不胜感激
干杯:)
这是一个大学项目,严格禁止使用数组,以防你想知道我为什么不使用数组
# 1 楼答案
您有一个
Product
类,它允许您创建Product
对象来保存您试图在这里使用的数据。然后,你可以简单地改变你的方法如下:不要使用输入中的产品名称,而是创建一个
Product
属性,该属性包含产品名称。将你的产品传递给方法,这样你就可以按照你想要的方式使用它们