尝试解决此编译错误,但无法理解它为什么显示。 在一个类(类 - 帐户)中,我定义了一个产品数组:
private Product[] productList; //List of products for a customer
并写了这个函数:
//Prints all products entered to the account
public void printAllProducts()
{
int i = 0;
while (i<this.productCounter)
{
printProduct(this.productList[i]);
i++;
}
}
当然也在Account类中写了一个printAllProduct函数:
//print specific product
public void printProduct(Product printMe)
{
System.out.println("in printProduct");
}
但是不断收到编译错误:
The method printProduct(Product) is undefined for the type Account
这是完整的“帐户”类:
package Q2;
import java.util.Scanner;
public class Tester {
public static void main(String[] args)
{
int[] x;
Scanner scan = new Scanner(System.in);
System.out.println("Hello");
System.out.println("-------------------------");
System.out.print("Enter the amount the Cashier start with or 0 for Zero amount to start with: ");
int startAmount = scan.nextInt();
Cashier newCashier; //create new cashier object with or without a start amount
if (startAmount>0)
{
newCashier = new Cashier(startAmount);
}
else
{
newCashier = new Cashier();
}
System.out.print("Enter new Customer name: "); //create a new customer
String name = scan.next();
Account newAccount = new Account(name);
int hasMore = 1; // New customer has at least 1 product, when hasMore = 0 purchase has finish and customer has no more products to buy
do
{
newAccount.addNewProduct();
//checking if there are more products for this customer
System.out.println("Enter 1 if the customer has another product or 0 to finish purchase");
hasMore = scan.nextInt();
} while (hasMore!=0);
newAccount.printAllProducts(); //Check method that prints all products for a customer
}
}
这是完整的“产品”类:
package Q2;
import java.util.Scanner;
//Class for product
public class Product
{
private String name; //name of a product
private int amount; //amount from a given product
private int price; //price of a given product
public Product()
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the name of the product: "); //Start getting details about new product
this.name = scan.next();
System.out.print("Enter the amount: ");
this.amount = scan.nextInt();
System.out.print("Enter the price: ");
this.price = scan.nextInt();
}
//print specific product
public void printProduct(Product printMe)
{
System.out.println("in PrintMe");
}
}
答案 0 :(得分:0)
你自己说:
当然在类Product
中写了一个printAllProduct函数
所以你需要使用
Product product = this.productList[i];
product.printProduct(this.productList[i]);
这表明存在设计问题。为什么Product类中的方法printProduct()
会将另一个Product作为参数?它应该只是
Product product = this.productList[i];
product.print();
print()
方法会打印出被调用的产品(例如this
)。
答案 1 :(得分:0)
好 我成功修复它现在它的工作原理, 我真的不明白为什么它没有按照我写的第一种方式工作。 为什么我不能只使用()中的参数启动一个函数,并且必须处理&#34;这个。&#34;
这是有效的代码:
//Prints all products entered to the account
public void printAllProducts()
{
int i = 0;
Product ProductToPrint;
do
{
ProductToPrint = this.productList[i];
ProductToPrint.printProduct();
i++;
}while (i<this.productCounter);
}