面向对象程序中的空指针错误

时间:2014-03-01 00:30:54

标签: java nullpointerexception

我正在开发一个程序,它将用户的输入转换为一个保存在单独类中的数组,然后从文件中获取数据并输入到同一个数组中。 我遇到的问题是代码编译但是我在调​​用addStock时在main中收到了一个空指针错误以及addStock中的第一个while语句。 谢谢你的帮助。

INVENTORY.JAVA

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    //program skeleton is based on previous inventory.java(v 1.0) which was in turn based on        divider.java(v 1.0)
    //item data is now moved into a stock array using the stock.class,see stock.java notes   for info on its implementation.
    public class Inventory
    {
    private static int MAX_ITEMS = 100; //change based on total # of unique items
    private Stock[] d_list; //creation of Stock array object
    private int d_nextItem; //used to count total # of unique items

    //constructor for inventory
    public Inventory(){
       d_list = new Stock[MAX_ITEMS];
       d_nextItem = 0;
    }

    //user imputs item and info and is inputed into stock array d_list
    //not used
    public void addStock(String name, String identifier, int quantity,
                        double unitCost, double sellingPrice ){

      Scanner keyboard = new Scanner(System.in);

      name = null;
      identifier = null;
      quantity = 0;
      unitCost = 0.0;
      sellingPrice = 0.0;
      String answer = null;
      String cont = null;

      while(!answer.equals("yes") && !answer.equals("no")){
         System.out.println("do you want to input an additional item into the stock manually?(yes or no)");
         answer = keyboard.next();
         if(!answer.equals("yes") && !answer.equals("no")){
            System.out.println("you must enter yes or no");
         }
      }
      if(answer.equals("yes")){
         while(cont.equals("yes")){ //having an error here
            System.out.println("Enter the name of the item");
            name = keyboard.next();
            System.out.println("Enter the id tag");
            identifier = keyboard.next();
            System.out.println("Enter the quantity of "+name);
            quantity = keyboard.nextInt();
            System.out.println("Enter the Cost for the item");
            unitCost = keyboard.nextDouble();
            System.out.println("Enter the sales price of the item");
            sellingPrice = keyboard.nextDouble();
            System.out.println("do you want to enter info for a second item?");
            while(!cont.equals("yes") && !cont.equals("no")){
               cont = keyboard.next();
               System.out.println("you must enter yes or no");
            }
            d_list[d_nextItem] = new Stock(name, identifier, quantity, unitCost, sellingPrice);
            d_nextItem += 1;
         }
      }
      return;
    }

    public void loadInventory(String fileName)
    throws FileNotFoundException{
      if ( (fileName != null) && (!fileName.equals("")) ){
         Scanner ldInv = new Scanner(new File(fileName));
         String newLine = null;

         //initialization for variables
         String name = null;
         String identifier = null;
         int    quantity = 0;
         double unitCost = 0.0;
         double sellingPrice = 0.0;

         //reading of file into the Stock array
         while (ldInv.hasNextLine() && d_nextItem < MAX_ITEMS){
            if (ldInv.hasNextDouble()){
               System.err.println("Error:NO name of product detected!");
               System.exit(2);
            } else {
               name = ldInv.next();
            }
            if (ldInv.hasNextDouble()){
              System.err.println("Error:NO product identifier detected!");
              System.exit(2);
            } else {
               identifier = ldInv.next();
            }
            if (ldInv.hasNextInt()){
               quantity = ldInv.nextInt();
            } else {
               System.err.println("Error: Quantity of item is missing!");
               System.exit(2);
            }
            if (ldInv.hasNextDouble()){
               unitCost = ldInv.nextDouble();
            } else {
               System.err.println("Error: Price of Item is missing!");
               System.exit(2);
            }
             if (ldInv.hasNextDouble()){
               sellingPrice = ldInv.nextDouble();
            } else {
               System.err.println("Error: Sales price of Item is missing!");
               System.exit(2);
            }
            d_list[d_nextItem] = new Stock(name, identifier, quantity, unitCost, sellingPrice);
            newLine = ldInv.nextLine();
            d_nextItem += 1;
         }
      }
      if (d_nextItem == 0){
         System.err.println("There is no data in this file");
         System.exit(2);
      }
      return;
    }

    //prints onto screen data taken from file in a format to align with headings
    public void printInventory(){
      System.out.println();
      System.out.println(d_list[0]);
      for (int i = 0; i < d_nextItem; i++){
         Stock stock = d_list[i];
          System.out.format("%-20s\t%9s\t%1d\t%9.2f\t%9.2f\t%9.2f\t%9.2f\n",
stock.getName(),
                           stock.getIdentifier(), stock.getQuantity(), stock.getUnitCost(),
                           stock.getSellingPrice(), stock.getTotalCost(), stock.getTotalSellingPrice());
      /*
         System.out.println(stock.getName() + "\t" + stock.getIdentifier() + "\t" +
                            stock.getQuantity() + "\t" + stock.getUnitCost() + "\t" +
                            stock.getSellingPrice() + "\t" + stock.getTotalCost() +
                            "\t" + stock.getTotalSellingPrice());
      */

      }
      return;
    }
    //calculates total value of all items from the file
    public double getTotalSalesPrice(){
      double totalSP = 0.0;
      for (int i = 0; i < d_nextItem; i++){
         Stock stock = d_list[i];
         totalSP += stock.getTotalSellingPrice();
      }

      return totalSP;
    }
    //calculates total cost of all items from the file
    public double getTotalCost(){
      double totalV = 0.0;
      for (int i = 0; i < d_nextItem; i++){
         Stock stock = d_list[i];
         totalV += stock.getTotalCost();
      }

      return totalV;
    }
    /*
     //user inputs name returns info from stock
    //not used
    public Stock getStock(String name){
    }
    */
    public static void main(String[] args) throws FileNotFoundException{
      String name = null;
      String identifier = null;
      int quantity = 0;
      double unitCost = 0.0;
      double sellingPrice = 0.0;
      if (args.length!=1){
             System.err.println("Usage:java Inventory <input file name>");
             System.exit(1);
          }
      Inventory inventory = new Inventory();
      inventory.addStock(name, identifier, quantity, unitCost, sellingPrice);
      inventory.loadInventory(args[0]);
      inventory.printInventory();
      System.out.format("\nTotal potential sales from inventory = %6.3f\n",
                        inventory.getTotalSalesPrice());
      System.out.format("\nTotal store cost of inventory = %6.3f\n",
                        inventory.getTotalCost());

     }
    }

stock.java

public class Stock{
private String d_name;
private String d_identifier;
private int    d_quantity;
private double d_unitCost;
private double d_sellingPrice;

public Stock(String name, String identifier, int quantity,
            double unitcost, double sellingprice){
  d_name = name;
  d_identifier = identifier;
  d_quantity = quantity;
  d_unitCost = unitcost;
  d_sellingPrice = sellingprice;
}
public String getName(){
  return d_name;
}
public String getIdentifier(){
  return d_identifier;
}
public int getQuantity(){
  return d_quantity;
}
public double getUnitCost(){
  return d_unitCost;
}
public double getSellingPrice(){
  return d_sellingPrice;
}
//sets the quantity of an item
public void setQuantity(int quantity){
  d_quantity = quantity;
}
//returns calculation of total cost of one type of item
public double getTotalCost(){
  return (d_quantity*d_unitCost);
}
//returns calculation of total sales value of one type of item
public double getTotalSellingPrice(){
  return (d_quantity*d_sellingPrice);
}
public String toString(){
 //this is the form the string must fit
 //System.out.format("%-20s\t%9s\t%1d\t%9.2f\t%9.2f\t%9.2f\t%9.2f\n"
 return "Product Name,           Identifier,     Quantity,   Unit Cost,      Selling Price,  Total Cost,     Total Selling Price";
}
public static void main(String[]args){
  Stock stock = new Stock("movie", "0a1b2c3d4", 5, 10, 20);

  System.out.println(stock);
  System.out.format("%-20s\t%9s\t%1d\t%9.2f\t%9.2f\t%9.2f\t%9.2f\n", stock.getName(),
                    stock.getIdentifier(), stock.getQuantity(),
                    stock.getUnitCost(), stock.getSellingPrice(),
                    stock.getTotalCost(),stock.getTotalSellingPrice());
  return;
}

5 个答案:

答案 0 :(得分:2)

您正在将answer设置为null,然后再拨打电话

answer.equals("yes")

抛出空指针异常,因为answer为空。

您应该将其设置为非空状态,如空字符串或其他人注意到的,在比较之前请求输入,以便它绝对是非空的,或者使用Yoda风格的等于检查

"yes".equals(answer)

答案 1 :(得分:1)

您正在将answer设置为null,然后将其与某些String值进行比较。这没有意义。在将它与任何内容进行比较之前,您可能希望将某些输入(例如System.in)读入变量answer

答案 2 :(得分:1)

让我们从您的代码块开始。

String answer = null;
String cont = null;

while(!answer.equals("yes") && !answer.equals("no")){

第1行:您将答案设为空

第3行:您查询答案是否等于某事。

现在,关于java的一点注意事项。 Null是一种类型,就像String一样。但是,Null是任何其他类型的子集。这意味着当你问

answer.equals()

你真的对java,new String(answer).equals()说。 由于答案实际上是null类型,因此java会将您的代码解释为new Null().equals()

问题是,类型null没有方法。所以它抛出一个NullPointerException因为你永远不能在null类型的任何东西上调用方法。

答案 3 :(得分:0)

您正在明确设置String answer = null,然后立即尝试在while循环中调用方法(您执行answer.equals...)。

考虑到程序这一部分的逻辑,你应该安全地使用do...while循环。像这样:

do{
    // get user input, set answer variable
while(answer.equals("yes") && !answer.equals("no"));

答案 4 :(得分:0)

在使用while循环时不要将answer声明为null,请先尝试读取输入或使用(" ")之类的无效内容初始化它,这些内容将无法识别但已初始化字符串{{1} }