-2

我正在编写一个代码,其中有一个 ArrayList 输入,并且从该 ArrayList 中我必须从中获取两个数字并减去它们。当我这样做时,我得到一个找不到符号错误。为什么我会收到此错误?

public static double[] profits( ArrayList<MenuItem> items )
{
 double[] lol = new double[items.size()];
 for ( MenuItem z : items )
  {
     for ( int i = 0; i < lol.length  ; i++ )
      {
        lol[i] = roundMoney(getPrice() - getCost());
      }
    return lol;
  }
}

这是主要课程:

     ArrayList<MenuItem> items = new ArrayList<MenuItem>();
    items.add( new MenuItem( "Alliteration Armadillo", 20.25, 3.15, 1, true ) );
    items.add( new MenuItem( "Consonance Chameleon", 5.45, 0.75, 0, false ) );
    items.add( new MenuItem( "Assonance Bass", 1.95, 0.50, 1, false ) );

    double[] t = profits( items );

    for ( double d : t )
      System.out.print( printAmount( d ) + " " );

我的输出应该是一个双精度数组,应该输出 {17.10 4.70 1.45}

The error says:

TC1.java:17: cannot find symbol 

symbol  : method getPrice()

If this isn't enough information then here is the whole class:

public class MenuItem 
{ 
  private String myName; 

  private double myPrice, 
                 myCost; 

  private int    myCode; 

  private boolean myAvailability; 

  public MenuItem( String name, double price, double cost, int code, boolean available ) 
  { 
    myName = name; 
    myPrice = price; 
    myCost = cost; 
    myCode = code; 
    myAvailability = available; 
  } 

  public String getName() { return myName; } 
  public double getPrice() { return myPrice; } 
  public double getCost() { return myCost; } 
  public int getCode() { return myCode; } 
  public boolean available() { return myAvailability; } 

  // Create your method here 
  public String menuString() 
  { 
  return getName() + " ($" + getPrice() + ")"; 
  } 

  public static double roundMoney( double amount ) 
  { 
    return (int)(100 * amount + 0.5) / 100.0; 
  } 

  public static String printAmount( double d ) 
  { 
    String s = "" + d; 
    int k = s.indexOf( "." ); 
    if ( k < 0 ) 
      return s + ".00"; 
    if ( k + 1 == s.length() ) 
      return s + "00"; 
    if ( k + 2 == s.length() ) 
      return s + "0"; 
    else 
      return s; 
  } 
} 

F

4

2 回答 2

4

在第一个代码片段中,将getPrice()andgetCost()替换为z.getPrice()and z.getCost()

现在,要获得您想要的输出,请将第一个片段修复为:

public static double[] profits(ArrayList<MenuItem> items)
{
    double[] lol = new double[items.size()];
    int i = 0;
    for (MenuItem z : items)
    {
        lol[i] = roundMoney(z.getPrice() - z.getCost());
        i++;
    }
    return lol;
}
于 2012-08-01T03:22:16.810 回答
1

您忘记使用z类型的对象引用变量MenuItem来访问其方法getPrice()getCost()

z点运算符一起使用来调用该方法。

例如:

z.getPrice()z.getCost()

于 2012-08-01T03:28:11.313 回答