如何按产品[计数器] .getProductTitle()进行数组排序?

时间:2009-08-22 00:53:03

标签: java

问题:productArray来自哪里:

for ( Product product : productArray )

&安培;

Arrays.sort( productArray, new ProductComparator() );

问题:我做错了什么?我该怎么做?

昨天的相关Post


                                 EDIT

::: EDIT ::: 好的,我在这里听取了你的建议

Product productArray[] = new Product[ARRAY_LENGTH]

现在它已经破了

/tmp/jc_22339/InventoryPart2.java:99: cannot find symbol
symbol  : variable productArray
location: class InventoryPart2
    for ( Product product : productArray ) {
                            ^
/tmp/jc_22339/InventoryPart2.java:101: cannot find symbol
symbol  : variable productArray
location: class InventoryPart2
        inventoryValue += productArray.calcInventoryValue();
                          ^

如果我这样做

for ( Product product : productArray[] ) {

我得到了

/tmp/jc_23524/InventoryPart2.java:69: '.class' expected
    for ( Product product : productArray[] ) {
                                           ^

所以我被困了。


开始计划

:::更新代码:::

    /**
 This program stores a collection of a product and its variables in a java array
 It will sort and display the information with a total
 */

// Import statements go here
import java.util.Scanner;// Import and use scanner
import java.util.Arrays;


public class InventoryPart2 {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {// begin main

        // Define your array of product objects and index here
        final int ARRAY_LENGTH = 5;// declare constant 
        final int version = 2;// declare int version number   

        // Create instance of Scanner class
        Scanner input = new Scanner( System.in );// new Scanner for CL input
        // Set counter to loop x times to populate your array of product objects
        int counter = 0;

        // Initialize your product array with the number of objects to populate it with
        Product productArray[] = new Product[ARRAY_LENGTH];// create array Product of class Product 

        // Welcome message
        System.out.printf( "\n%s%d\n" , 
        "Welcome to the Productentory Program v.", version );

        // Construct default values for Product
        productArray[0] = new Product("EThe Invisible Man", 0, 8.50);
        productArray[1] = new Product("DThe Matrix", 1, 17.99);
        productArray[2] = new Product("CSe7en", 7, 12.99);
        productArray[3] = new Product("BOceans Eleven", 11, 9.99);
        productArray[4] = new Product("AHitch Hikers Guide to the Galaxy", 42, 18.69);

        /*// Loop as many times as your counter variable
        {

            // Instantiate a product object

            // Prompt for product name and call the set method on your product object

            // Prompt for item number and call the set method on your product object

            // Prompt for units in stock and call the set method on your product object

            // Prompt for unit price and call the set method on your product object

            // store product object in array element

            //Destroy product object reference
            product = null;

            // Flush the buffer
            input.nextLine();

        }*/

        // Sort product array by product name using Comparator implementation class
        sortProductArray();

        // Print sorted array
        for ( Product product : productArray[] ) {
        if ( counter == 0 )
            System.out.printf( "\n%s\n", "Sorted Inventory of DVD movies");
        System.out.printf( "\n\n%s%d\n%s%s\n%s%d\n%s%,.2f\n%s%,.2f\n",
        "Item Number:      ",counter,
        "DVD Title:        ",productArray[counter].getProductTitle(),
        "Copies in stock:  ",productArray[counter].getUnitsInStock(),
        "Price each disk:  $",productArray[counter].getUnitPrice(),
        "Value of disks:  $",productArray[counter].calcInventoryValue());//End print
        counter++;  
        if ( counter == productArray.length)// on last counter of loop print total
            System.out.printf( "\n%s%,.2f\n\n\n",
            "Collection Value: $",calcTotalInventoryValue());
        }

        // Calculate total Inventory value

    }


 // method to calculate the total Inventory value
 private static double calcTotalInventoryValue()
 {

    double inventoryValue = 0;

    // Iterate array of product objects and calculate total value of entire Inventory
    for ( Product product : productArray ) {
        // accumulate inventory value from each product object in array
        inventoryValue += productArray.calcInventoryValue();
    }

     return totalInventoryValue;

 } // end method calcInventoryValue


 // method to sort product array
 private static void sortProductArray()
 {

    Arrays.sort( productArray, new ProductComparator() );



 } // end method calcInventoryValue


}

4 个答案:

答案 0 :(得分:3)

Product Product[] = new Product[ARRAY_LENGTH];

应该是这样的:

Product productArray[] = new Product[ARRAY_LENGTH];

- 编辑

您还需要更改引用此“变量”的相关行。

如果我建议,如果您对此感到困惑,请让您的老师/书籍更新“变量”。

不要担心,如果你没有得到它:继续问,直到你这样做。如果你有足够的兴趣去学习,你就会被淘汰。所以要感兴趣,提出问题,做自己的研究,生活会很好。

答案 1 :(得分:1)

我认为“productArray”应该是指您创建的产品数组。所以就行:

Product Product[] = new Product[ARRAY_LENGTH];// create array Product of class Product 

也改变它:

Product[] productArray = new Product[ARRAY_LENGTH];

答案 2 :(得分:1)

您必须拥有Product数组作为InventoryPart2类的成员或传递给sortProductArray方法。如果选择后者,则必须更改该方法以返回对已排序数组的引用。

您的Product数组位于静态main方法中,而不是对象的一部分,因此您遇到了问题。我建议你做这样的事情:

public class Inventory
{
    private static final int DEFAULT_INVENTORY_SIZE = 5;
    private Product [] products;
    private int numProducts;

    public Inventory()
    {
       this(DEFAULT_INVENTORY_SIZE);
    }

    public Inventory(int size)
    {
       products = new Product[size];
       numProducts = 0;
    }

    public void addProduct(Product p)
    {
       products[numProducts++] = p;

    }

    public void sort()
    {
        // sort the array here
    }

    public String toString()
    {
        StringBuilder builder = new StringBuilder(1024);

        // Create a string representation of you inventory here

        return builder.toString();
    } 
}

面向对象编程是关于封装和信息隐藏。以这样的方式编写类,使客户不必知道或关心您是使用数组还是其他东西来保留产品。你在这里抽象出了库存的想法。

更新:

这是你的代码,只有更好并且正在运行:

import java.util.Scanner;
import java.util.Arrays;

public class InventoryPart2
{
   public static void main(String[] args)
   {
      final int ARRAY_LENGTH = 5;
      final int version = 2;

      int counter = 0;

      Product productArray[] = new Product[ARRAY_LENGTH];

      System.out.printf("\n%s%d\n",
      "Welcome to the Productentory Program v.", version);

      productArray[0] = new Product("EThe Invisible Man", 0, 8.50);
      productArray[1] = new Product("DThe Matrix", 1, 17.99);
      productArray[2] = new Product("CSe7en", 7, 12.99);
      productArray[3] = new Product("BOceans Eleven", 11, 9.99);
      productArray[4] = new Product("AHitch Hikers Guide to the Galaxy", 42, 18.69);

      productArray = sortProductArray(productArray);

      // Print sorted array
      for (Product product : productArray)
      {
         if (counter == 0)
         {
            System.out.printf("\n%s\n", "Sorted Inventory of DVD movies");
         }
         System.out.printf("\n\n%s%d\n%s%s\n%s%d\n%s%.2f\n%s%.2f\n",
         "Item Number:      ", counter,
         "DVD Title:        ", product.getProductTitle(),
         "Copies in stock:  ", product.getUnitsInStock(),
         "Price each disk:  $", product.getUnitPrice(),
         "Value of disks:  $", product.calcInventoryValue());
         counter++;
      }
      System.out.printf("\n%s%,.2f\n\n\n",
      "Collection Value: $", calcTotalInventoryValue(productArray));
   }

   private static double calcTotalInventoryValue(Product[] productArray)
   {
      double inventoryValue = 0;

      for (Product product : productArray)
      {
         inventoryValue += product.calcInventoryValue();
      }

      return inventoryValue;

   }

   private static Product[] sortProductArray(Product[] productArray)
   {
      Arrays.sort(productArray, new ProductComparator());

      return productArray;
   }
}

我删除了您在任何地方添加的评论。他们只是杂乱无章;我建议你不要那样做了。通过使用更好的变量和方法名称,更好地使代码更具可读性和自我记录。

这仍然不是我建议您编写它的方式,但它有效。如果我不做太多修改,你就更有可能看到为什么会有效。

更新2:

万一你感兴趣,我的写作方式如下:

    import java.util.Scanner;
import java.util.Arrays;
import java.text.NumberFormat;

public class Inventory
{
   private static final int DEFAULT_LENGTH = 5;
   private static final int VERSION = 2;

   private Product[] products;
   private int numProducts;

   public static void main(String[] args)
   {
      Inventory inventory = new Inventory(5);

      inventory.addProduct(new Product("EThe Invisible Man", 0, 8.50));
      inventory.addProduct(new Product("DThe Matrix", 1, 17.99));
      inventory.addProduct(new Product("CSe7en", 7, 12.99));
      inventory.addProduct(new Product("BOceans Eleven", 11, 9.99));
      inventory.addProduct(new Product("AHitch Hikers Guide to the Galaxy", 42, 18.69));

      System.out.println(inventory);
      System.out.println("total value: " + NumberFormat.getCurrencyInstance().format(inventory.getTotalValue()));
   }

   public Inventory()
   {
      this(DEFAULT_LENGTH);
   }

   public Inventory(int size)
   {
      products = new Product[size];

      this.numProducts = 0;
   }

   public void addProduct(Product p)
   {
      products[numProducts++] = p;
   }

   public double getTotalValue()
   {
      double inventoryValue = 0.0;

      for (Product product : products)
      {
         inventoryValue += product.calcInventoryValue();
      }

      return inventoryValue;
   }

   public String toString()
   {
      StringBuilder builder = new StringBuilder(1024);
      String newline = System.getProperty("line.separator");

      if (products.length > 0)
      {
         Arrays.sort(products, new ProductComparator());
         for (Product product : products)
         {
            builder.append(product).append(newline);
         }
      }

      return builder.toString();
   }
}

答案 3 :(得分:0)

不要认为这里的每个人都能在几秒钟内发现语法错误。我们不是以这种方式出生的,我们只知道要寻找什么,因为我们犯了相同的错误数百次

所以,如果你确信你想成为一名程序员,即使你因为这样的东西而在你的智慧结束时, 就会被删除。奉献和激情远比自然人才重要。

抬起头来。下次你遇到困难我们会在这里。 :)