簡體   English   中英

我怎樣才能打印程序? 嘗試訪問.toString()時收到NullPointerException

[英]How can I get my program to print? I get a NullPointerException when I try to access .toString()

當我運行程序時,它給了我這個錯誤。 錯誤位於MergeInventories類以及CombInv類中。 我已經在下面提供的類中對它們進行了標記。

java.lang.NullPointerException
    at CombInv.print(CombInv.java:19)
    at MergeInventories.main(MergeInventories.java:17)

我只是想打印出數據。 我的程序本質上采用兩個數組,並對它們進行MergeSorts處理。

這是我程序的多個類。

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"));

            CombInv mergedInventory = mergeInventories(store1,store2);

            //store1.print();
            //store2.print();
            mergedInventory.print(); //********THIS IS LINE 17 OF THE ERROR*************
        }
        catch(Exception e)
        {
            e.printStackTrace();
            //System.out.print("Error.");
        }

    }

    private static CombInv mergeInventories(Inventory a, Inventory b)
    {
        CombInv inv = new CombInv();
        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("Varun Pinto \n8th Hour \nM359 AP Comp Sci \n");
    }
}

然后我們有庫存類

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

public class Inventory
{
    protected int increment = -1;
    protected int size = 0;
    protected Product[] inventory = new Product[11];
    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());
            increment+=1;
            inventory[increment]=p;
        }
    }

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

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

    public int 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();
    }
}

接下來,我找到了其中一個錯誤所在的CombInv類。

import java.text.*;

public class CombInv 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()));
//******THERE IS AN ERROR ON THE LINE ABOVE**************************
            total += p.getQty() * p.getUP();
        }

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

最后,我們有了Product類,它是一個基本的超類,在該類中,我嘗試訪問.toString()但不能。

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);
    }
}

請注意,在清單中使用ArrayList確實可以使該程序正常工作,但是由於這是一個項目,因此我不允許僅使用ARRAYLISTS數組。 另外,我必須使用MergeSort對數據進行排序。

這是我從中讀取數據的兩個文本文件: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

這是我希望打印的內容

My Name 
8th Hour 
M359 AP Comp Sci 

TOTAL INVENTORY                         //It only prints out
ID      QTY     U\P VALUE               //these two lines.
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

我花了一些時間來回答這個問題,因為我基本上推遲了最長的時間。 該錯誤是NullPointerException,我通過簡單添加以下內容對其進行了修復:

    if(p != null)

在我調用p.toString()的所有實例之前。 答案是如此簡單,以至於我不敢相信我對此一無所知,我所要做的就是檢查該值是否不是null,並且它將繼續循環直到找到實際值。 我知道我的合並排序工作了。 最后,這是一個非常簡單的修復程序,根本不需要我更改大量代碼。

另外,我還必須在Inventory類的構造方法的while循環中再次增加大小。 我忘了這樣做,但是盡管人們說過要重寫MergeSorter,但我的代碼仍然有效!

合並兩個排序列表時,也許應該考慮使用以下策略:

  • 考慮生成的排序列表的大小
  • 循環查看生成的合並列表的大小
  • 在每一步中,考慮下一步應使用哪個輸入列表元素
  • 確保處理元素的輸入列表“用完”

[作業..所以沒有提供代碼]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM