2014-04-03 3 views
-1

한 번에 3 개의 클래스를 작업하기 시작하면서 위와 같은 오류 메시지가 나타납니다. 나는 그것이 왜 보여지고 있는지에 대해 매우 혼란 스럽다. 나는 자바에 익숙하지 않아서 내가 볼 수없는 매우 쉬운 일이 될 수있다. addToCart 메소드 아래의 장바구니 클래스에서 오류가 발생합니다. 나는 이것들을 볼 물건이 많다는 것을 알지만, 나는 내가 얻을 수있는 모든 도움을 정말로 감사 할 것이다.왜 응용 프로그램이 NullPointerException을 던지고 있습니까?

public class ShoppingCart 
{ 
    private int itemCount;  //total number of items in the cart 
    private double totalPrice;  //total price of items in the cart 
    private final int MAXSIZE = 100; // cart maximum capacity 
    private Item[]cart; 

    //creates an empty shopping cart 
    public ShoppingCart() 
    { 
     Item[]cart = new Item [MAXSIZE]; 
     itemCount = 0; 
     totalPrice = 0.0; 
    } 

    //adds an item to the shopping cart 
    public void addToCart(String itemName, double price, int quantity) 
    { 

     cart[itemCount] = new Item(itemName, price, quantity); 
     totalPrice = (totalPrice + (quantity * price)); 
     itemCount++; 

    } 
    //returns the contents on the cart together with summary information 
    public String toString() 
    { 
     String contents = "\nShopping Cart\n"; 
     contents = contents + String.format("%-12s%-12s%-10s%-7s%n", "Item", 
     "Unit Price", "Quantity", "Item Total"); 

     for(int i = 0; i<itemCount; i++) 
     contents = contents + cart[i].toString() + "\n"; 

     contents = contents + String.format("%20s$ %.2fn","CurrentTotal:", totalPrice); 

     return contents; 
    } 

} 













import java.util.*; 

public class Shop 
    { 
    public static void main (String[] args) 
    { 
     ShoppingCart myCart = new ShoppingCart(); 
     Scanner kbd = new Scanner(System.in); 




     String itemName; 
     double itemPrice; 
     int quantity; 

     String keepShopping = "y"; 

     do 
     { 
      System.out.print ("Enter the name of the item: "); 
      itemName = kbd.nextLine(); 

      System.out.print ("Enter the unit price: "); 
      itemPrice = kbd.nextDouble(); 

      System.out.print ("Enter the quantity: "); 
      quantity = kbd.nextInt(); 

      myCart.addToCart(itemName, itemPrice, quantity); 

      System.out.print ("Continue shopping (y/n)? "); 
      keepShopping = kbd.next(); 
      kbd.nextLine(); 
     } 
     while (keepShopping.equals("y")); 

     System.out.println("Have a Nice Day!"); 

    } 
} 










import java.text.NumberFormat; 

public class Item 
{ 
    private String name; 
    private double unitPrice; 
    private int quantity; 

    // ------------------------------------------------------- 
    // Create a new item with the given attributes. 
    // ------------------------------------------------------- 
    public Item (String itemName, double itemPrice, int numPurchased) 
    { 
     name = itemName; 
     unitPrice = itemPrice; 
     quantity = numPurchased; 
    } 

    // ------------------------------------------------------- 
    // Return a string with the information about the item 
    // ------------------------------------------------------- 

    public String toString() 
    { 
     return String.format("%-15s$%-8.2f%-11d$%-8.2f", name, unitPrice, quantity,  unitPrice*quantity); 
    } 

    // ------------------------------------------------- 
    // Returns the unit price of the item 
    // ------------------------------------------------- 
    public double getPrice() 
    { 
     return unitPrice; 
    } 

    // ------------------------------------------------- 
    // Returns the name of the item 
    // ------------------------------------------------- 
    public String getName() 
    { 
     return name; 
    } 

    // ------------------------------------------------- 
    // Returns the quantity of the item 
    // ------------------------------------------------- 
    public int getQuantity() 
    { 
     return quantity; 
    } 
} 
+0

내가했을 때 올바르게 형식화되지 않았기 때문입니다. 그리고 내가 한 일은, didnt 일 그래서 사진을 게시해야만한다면 – user3494953

+0

볼 것이 많으면, 우리를 위해 일해주세요. 오류가 발생하지 않을 때까지 변경 사항을 실행 취소 한 다음 단일 클래스로 작업하십시오. 오류가 다시 발생할 때까지 변경 사항을 추가하십시오. 마지막으로 추가 한 것은 오류의 원인이며 거기에서 디버깅을 시작하십시오. –

+0

적어도 스택 추적을 게시 할 수 있습니다. 포맷 할 필요가 없습니다. – Veluria

답변

1

이 생성자 내부의 cart 배열

private Item[]cart; 

declaring, 당신은 그것을

public ShoppingCart() { 
    Item[]cart = new Item [MAXSIZE]; 
    itemCount = 0; 
    totalPrice = 0.0; 
} 

를 초기화되지만 여기 요소 중 하나에 액세스하려고 할 때 (cart[itemCount]는) 그것은 던졌습니다 NullPointerException

배열을 올바르게 선언하더라도 생성자가 끝나자 마자 바로 null으로 되돌아갑니다. 이 인스턴스의 scope은 생성자 본문 자체에 대해 로컬입니다. cart의 범위는 전체 클래스에 확장 되었기 때문에

변경

Item[] cart = new Item [MAXSIZE]; 

cart = new Item [MAXSIZE]; 

그런 다음,

cart[itemCount] = new Item(itemName, price, quantity); 

더 이상하는 NullPointerException가 발생하지 않습니다.

+0

정말 고마워요. 나는 직장에 있지만 지금은 확인할 수 없다.네가 무슨 말하는지 알거야. 답장을 보내신 모든 분들께 감사드립니다. – user3494953

+0

안녕하세요. 행운을 빌어 요. – aliteralmind

0

선언/인스턴스화되지 않은 변수를 참조하려는 경우 NullPointer 예외가 발생합니다. 예를 들어, 다음과 같이 선언 한 경우 : List newList; 그런 다음 시도 : newList.add (item); 새 목록이 인스턴스화되지 않았으므로 예외가 발생합니다. addToCart() 함수에서 throw하는 경우 사용중인 변수 중 하나가 선언되지 않았거나 인스턴스화되지 않았기 때문에 가능성이 큽니다. 디버깅하고 각 변수의 값을 인쇄하여 해당 함수 호출에 연결하여 값이 연결되어 있는지 확인합니다. 그들이 그렇게하지 않으면 당신의 문제 일 수 있습니다. 여기

관련 문제