2014-03-01 7 views
-3

사용자로부터 입력을 별도의 클래스에 보관 된 배열로 가져간 다음 파일에서 데이터를 가져 와서 동일한 배열에 입력하는 프로그램에서 작업하고 있습니다. imakening 문제는 코드가 컴파일되지만 addStock에 대한 호출에서 main에 널 포인터 오류가 발생하고 addStock에서 첫 번째 while 문이 발생한다는 것입니다. 도움을 주셔서 감사합니다.null 포인터 객체 지향 프로그램의 오류

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; 
} 
+2

당신을 초기화했다 (" ") 같은 유효하지 않은 뭔가를 초기화 'String answer = null;'을 명시 적으로 설정하고 있습니다. 왜 그것이 사람들이 거주 할 것으로 기대합니까? –

+0

사이드 노드로서'name','identifier','quantity','unitCost' 및'sellingPrice'를'addStock()'의 매개 변수로 전달하는 이유를 모르겠습니다. 함수의 시작. –

답변

1

당신은 answernull에 설정하고 비교하는 몇몇 String 값에 대하여. 그건 말이되지 않습니다. 예를 들어, System.in의 일부 입력을 변수 answer에 입력 한 다음 그 값을 비교하기를 원할 수도 있습니다.

2
당신은 nullanswer를 설정 한 다음 전화 answer가 null 때문에 널 포인터 예외가 발생

answer.equals("yes") 

를 호출 할

.

당신은 빈 문자열 같은 것을 null 이외로 설정하거나 다른 사람이 언급 한 것처럼, 그것은 확실히 null 이외의 그래서, 비교하기 전에 입력을 요구하거나 요다 스타일의 확인과 같다 사용해야 하나

"yes".equals(answer) 
1

코드 블록으로 시작하십시오.

String answer = null; 
String cont = null; 

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

은 1 호선 : 당신은 대답이

3 호선을 null로 설정 : 당신은 뭔가 동일 있는지 답을 쿼리합니다.

이제 자바에 대한 약간의 설명이 있습니다. NullString과 같은 형식입니다. 그러나 Null은 다른 유형의 하위 집합입니다. 이것이 의미하는 것은 당신이

answer.equals()

를 요청할 때 당신이 정말로 자바, new String(answer).equals()을 말하는 것입니다. 대답은 유형 null의 사실이기 때문에, 자바는 문제가 new Null().equals()

로 코드를 interpretting되고, 유형 null에는 방법이 없습니다. 따라서 유형의 메소드를 절대 호출 할 수 없기 때문에 NullPointerException을 던집니다.

0

명시 적으로 String answer = null을 설정 한 다음 while 루프에서 해당 메서드를 즉시 호출하려고 시도합니다 (여기서 answer.equals...).

프로그램의이 부분의 논리를 감안할 때 do...while 루프를 사용하는 것이 안전해야합니다.그래서 같이 :

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

는 while 루프를 사용하는 반면에 null answer를 선언 해달라고 먼저 입력을 읽어보세요 또는 인식되지 않습니다하지만 문자열 answer