【问题标题】:How can I replace the ArrayList in my code with an Array and still have it work?如何将代码中的 ArrayList 替换为 Array 并且仍然可以正常工作?
【发布时间】:2014-04-20 13:01:20
【问题描述】:

我有一个计算机程序,我必须在其中从两个文本文件中读取代码,然后使用合并排序来合并然后对两个文本文件进行排序。我不能只是将两个库存背靠背放入一个数组并排序!我的代码适用于 ArrayLists,因此我将它们注释掉并在必要时用 Array 和其他 Array 元素替换它们,所有更改都对 Inventory 类进行。编译时没有语法错误,但是我的 try catch 发现错误。

这是两个文本文件:
Store1.txt

STORE 1 INVENTORY
ID  QTY U/P       
362 5   12.98
471 2   6.70
792 13  25.00
901 7   2.98

和 Store2.txt

STORE 2 INVENTORY
ID  QTY U/P
163 4   7.20
209 5   11.98
471 5   6.70
608 4   5.90
627 2   9.99
792 1   25.00
812 4   6.00

我有多个课程。这是我从中编译程序的测试器类

import java.io.*;

public class MergeInventories
{
    public static void main()
    {
        header();
        try
        {
            Inventory store1 = new Inventory(new File("F:\\M359 AP Computer          Science\\JAVA\\Merge Inventories\\Store1.txt"));
            Inventory store2 = new Inventory(new File("F:\\M359 AP Computer Science\\JAVA\\Merge Inventories\\Store2.txt"));

            CombinedInventory mergedInventory = mergeInventories(store1,store2);

            store1.print();
            store2.print();
            mergedInventory.print();
        }
        catch(Exception e)
        {
            System.out.print("Error.");
        }

    }

    private static CombinedInventory mergeInventories(Inventory a, Inventory b)
    {

        CombinedInventory inv = new CombinedInventory();

        int i=0,j=0,k=0;

        while(i<a.size()&&j<b.size())
        {
            if(a.getProduct(i).getID() == b.getProduct(j).getID())
            {
                inv.add(new     Product(a.getProduct(i).getID(),a.getProduct(i).getQty()+b.getProduct(j).getQty(),a.getProduct(i).getUP()));
                i++;
                j++;
            }
            else if(a.getProduct(i).getID() > b.getProduct(j).getID())
            {
                inv.add(b.getProduct(j));
                j++;
            }
            else
            {
                inv.add(a.getProduct(i));
                i++;
            }
            k++;
        }

        if(j<b.size())
        {
            for(j=j;j<b.size();j++)
            {
                inv.add(b.getProduct(j));
            }
        }
        else if(i<a.size())
        {
            for(i=i;i<a.size();i++)
            {
                inv.add(a.getProduct(i));
            }
        }
        return inv;
    }

    private static void header()
    {
        System.out.println("My Name \n8th Hour \nM359 AP Comp Sci \n");
    }
}

库存类别:

import java.util.*;
import java.io.*;

public class Inventory
{
    protected int increment = -1;
    protected int size = 0;
    protected Product[] inventory = new Product[20];
    //protected ArrayList<Product> inventory = new ArrayList<Product>();
    protected String header;
    protected static String CATEGORIES = "ID\tQTY\tU\\P";

    public Inventory()
    {
        header = "TOTAL INVENTORY";
    }

    public Inventory(File file)throws FileNotFoundException
    {
        Scanner fileScan = new Scanner(file);
        header = fileScan.nextLine();
        String throwaway = fileScan.nextLine();
        while(fileScan.hasNextLine())
        {
            Scanner lineScan = new Scanner(fileScan.nextLine());
            Product p = new Product(lineScan.nextInt(), lineScan.nextInt(), lineScan.nextDouble());
            add(p);
        }
    }

    public void add(Product p)
    {
        inventory[increment++]=p;
        //inventory.add(p);
        size++;
    }

    public Product getProduct(int i)
    {
        //return inventory.get(i);
        return inventory[i];    
    }

    public int size()
    {
        //return inventory.size();
        return size;
    }

    public void print()
    {
        System.out.println(header);
        System.out.println(CATEGORIES);
        for(Product p: inventory)
        {
            System.out.println(p.toString());
        }
        System.out.println();
    }
}

这个类结合了库存

import java.text.*;

public class CombinedInventory extends Inventory
{
    public void print()
    {
        System.out.println(header);
        System.out.println(CATEGORIES + "\tVALUE");

        double total = 0;

        NumberFormat f = NumberFormat.getNumberInstance();
        f.setMinimumFractionDigits(2);
        f.setMaximumFractionDigits(2);

        for(Product p: inventory)
        {
            System.out.println(p.toString() + "\t" + f.format(p.getQty() * p.getUP()));
            total += p.getQty() * p.getUP();
        }

        System.out.println("Total Value of Stock:\t$" + total);
        System.out.println();
    }
}

最后我们有了一个基本的超类

import java.text.*;

public class Product
{
    private int idNum;
    private int quantity;
    private double unitPrice;

    public Product()
    {
        idNum = 0;
        quantity = 0;
        unitPrice = 0;
    }

    public Product(int id, int q, double price)
    {
        idNum = id;
        quantity = q;
        unitPrice = price;
    }

    public int getID()
    {
        return idNum;
    }

    public int getQty()
    {
        return quantity;
    }

    public double getUP()
    {
        return unitPrice;
    }

    public String toString()
    {
        NumberFormat f = NumberFormat.getNumberInstance();
        f.setMinimumFractionDigits(2);
        f.setMaximumFractionDigits(2);

        return idNum + "\t" + quantity + "\t" + f.format(unitPrice);
    }
}

这是我希望打印出来的内容

My Name 
8th Hour 
M359 AP Comp Sci 

STORE 1 INVENTORY
ID      QTY     U\P
362     5       12.98
471     2       6.70
792     13      25.00
901     7       2.98

STORE 2 INVENTORY
ID      QTY     U\P
163     4       7.20
209     5       11.98
471     5       6.70
608     4       5.90
627     2       9.99
792     1       25.00
812     4       6.00

TOTAL INVENTORY
ID      QTY     U\P VALUE
163     4       7.20    28.80
209     5       11.98   59.90
362     5       12.98   64.90
471     7       6.70    46.90
608     4       5.90    23.60
627     2       9.99    19.98
792     14      25.00   350.00
812     4       6.00    24.00
901     7       2.98    20.86
Total Value of Stock:   $638.94

但是,不是打印所有值,而是打印出“错误”。我不明白为什么会这样。如何使用 Arrays 而不是 ArrayList 让它工作?

【问题讨论】:

  • 你做了什么来调试它?
  • 使用 e.printStackTrace() 而不是 System.out.print("Error.")。它会告诉你具体的异常和它发生的行。
  • 如果ArrayList 适合您,为什么要替换为数组开头?
  • 为什么要使用数组而不是ArrayList?你知道你会提前有多少产品吗?您可以将这两个清单放入一个 Collection,实现 Comparator 和 Comparable,然后将它们传递给 Collections.sort。它们不需要在要排序的数组中。
  • 项目要求声明我必须使用 ArrayLists

标签: java arrays sorting arraylist text-files


【解决方案1】:

如果它与 ArrayList 一起使用,则不必创建数组。如果你真的想要数组,你可以做 theArrayList.toArray();

ArrayList 更简单,也更面向对象。

【讨论】:

  • OP 知道它适用于 ArrayList,他正在询问替换列表时面临的问题。
猜你喜欢
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 2020-07-07
  • 1970-01-01
  • 2014-04-08
相关资源
最近更新 更多