试图在NetBeans中告诉我这个错误是什么?

时间:2013-08-04 01:01:23

标签: java user-interface netbeans compiler-errors

所以我一直在研究我的程序,在java中第一次使用GUI。我想我拥有应有的一切,但却给了我一个错误:

Exception in thread "main" java.lang.NullPointerException
    at GUIProgram.<init>(GUIProgram.java:41)
    at Inventory.main(Inventory.java:12)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)

我不知道我到底要做什么,我一直在努力修复它,但我不能。

如果您需要更多信息以找出问题所在,请告知我们。

修改(从评论中复制)

Product[] array = new Product[table.length]; 
float total = 0; float fee = 0; 
for(Product p: array) { 
  total += p.getTotal(); 
  fee += p.getRestockingFee();
}

这是我正在构建的GUIProgram类。

    import javax.swing.*;
import java.awt.*;

public class GUIProgram extends JFrame
{

     public GUIProgram()
     {
        super("Welcome to the Inventory Program");

        setLayout(new FlowLayout());

        String[] columnNames = {"Item", "Item No.", "Unit", "Price"};


        Product[] table = new Product[5];

        table[0] = new Product("chocolate", 1023, 124, 1.50f);
        table[1] = new Product("ice cream", 1543, 170, 3.35f);
        table[2] = new Product("milk", 1265, 230, 2.40f);
        table[3] = new Product("orange juice", 1653, 199, 0.60f);
        table[4] = new Product("cereal", 1534, 176, 3.50f);

        for (int i = 0; i < table.length; i++)
        {
         JTextField textfield1 = new JTextField(table.length);
         add(textfield1);

           float total = 0;
           float fee = 0;

           for(Product p: table)
           {
                 total += p.getTotal();
                 fee += p.getRestockingFee();

            }

           JTextField textfield2 = new JTextField(table.length);
           textfield2 = new JTextField(String.format("The total value of the Fruits Inventory is: %.2f", total));
           add(textfield2);

           JTextField textfield3 = new JTextField(table.length);
           textfield3 = new JTextField(String.format("The total restocking fee is: %.2f", fee));
           add(textfield3);
         }     
     }  
}

我只是想为这个数组构建一个GUI。

2 个答案:

答案 0 :(得分:2)

它说有一个名为GUIProgram.java的源文件,其第41行在null引用上有一些方法调用

通过

Product[] array = new Product[table.length]; 

您声明您将拥有一个Product数组,并且您现在可以在table.lengh数组中使用数据

所有这些引用仍为null,您需要初始化每个产品

并且这样做

for(Product p: array) { 
  // initialization
  p = new Product();
  total += p.getTotal(); 
  fee += p.getRestockingFee();
}

答案 1 :(得分:1)

在初始化之前,您似乎在构造函数中使用了一个变量。

随机示例:

Button runButton; //declared, but not initialized
button.SetColor(0, 0, 0); //calling the SetColor method on the uninitialized variable will cause it to go bang and give you a NullPointerException
相关问题