2013-10-22 2 views
-1

이 프로그램을 작성했지만 컴파일시 논리적 오류가 발생합니다. index.arrayOutOfBounds를 얻고 싶습니까?오류 : ArrayOutOfBounds. 해결 방법?

내 입력이 제품의 선택 1, 2, 6, 10 것과 일치 출력 오류가이 출력에 선도 루프 조건이나 계산, 또는 내 배열 내에서 거기에

Total items ordered: 3 
Price of items ordered: $747.00 
Sales Tax: $48.55 
Total amount due: $795.55 

해야 하는가?

import java.util.Scanner; 
public class GrapefruitOrderingArray { 

//Declare Constants 
public static final int SIZE = 100; 
public static final int[] itemPrices = {49,299,329,399,199,1299,1199,999,599}; 

public static void main(String[] args) { 
// Declare Variables 
    Scanner input = new Scanner (System.in);          
    String CustomerName;              
    int[] naNumber = new int [SIZE];            
    int nProducts = 0;               
    double nTotal = 0;               
    double dFinalPrice = 0.0;             
    int nCount = 0;                

    //Declare Constants 
    final int SENTINEL = 10; 
    final double SALES_TAX = 0.065; 

    //Prompt user to enter name 
    System.out.println("Please enter your name: "); 

    //Enter user name 
    CustomerName = input.nextLine(); 

    System.out.println(""); 

    //Begin Product Listing Declarations with respect to array above 
    System.out.println("GRAPEFRUIT PRODUCT:"); 
    System.out.println("1. gPod shuffle $" + itemPrices[0]); 
    System.out.println("2. gPod Touch $" + itemPrices[1]); 
    System.out.println("3. gPad Mini $" + itemPrices[2]); 
    System.out.println("4. gPad 2  $" + itemPrices[3]); 
    System.out.println("5. gPhone  $" + itemPrices[4]); 
    System.out.println("6. gMac   $" + itemPrices[5]); 
    System.out.println("7. MacNovel Pro $" + itemPrices[6]); 
    System.out.println("8. MacNovel Air $" + itemPrices[7]); 
    System.out.println("9. MiniMac  $" + itemPrices[8]); 
    System.out.println("10. Complete my order"); 

    //Keep reading until the input is terminated by sentinel 
    System.out.println("\nPlease select an item from the menu above: "); 

    //Read number entered by the user 
    naNumber[nCount] = input.nextInt(); 

    //Begin while-loop statement 
    while (naNumber[nCount] != SENTINEL) { 

    System.out.println("\nPlease select another item from the menu above: "); 

    nCount++; 

    //Read number entered by the user 
    naNumber[nCount] = input.nextInt(); 
} 

    System.out.println("Thank you for ordering with Grapefruit Company, " + CustomerName); 
     //Call final price calculation 
     dFinalPrice = calculateTotalPrice(naNumber,itemPrices,nTotal); 

      //Print blank line to screen 
      System.out.println(""); 

      //Total amount of product ordered 
      System.out.println("Total items ordered: " + nCount); 

      //Total price of items ordered 
      System.out.println("Price of items ordered: $" + dFinalPrice); 

      //Sales tax associated with the purchase 
      System.out.println("Sales tax: $" + SALES_TAX * dFinalPrice); 

      //Total amount due by the customer to Grapefruit Co. 
      System.out.println("Total amount due: $" + (SALES_TAX * dFinalPrice + dFinalPrice)); 
    } //End main method 

private static double calculateTotalPrice(int[] naNumber, int[] itemPrices) { 

    double total = 0; 

    //Calculate entered items 
    for(int i = 0; i < naNumber.length; i++){ 
    if(naNumber[i] != 0) { 
    total += itemPrices[naNumber[i] - 1]; 
    } 
} 

    return total; 
    } 
} //end class calculateTotalPriceOfItemsOrdered 
+2

디버거 사용을 고려하십시오. –

+0

스택 추적이란 무엇입니까? 괜찮은 IDE는 예외에 대한 행을 표시합니다. IDE가 즉시 수행 할 수있는 작업을 디버깅하는 것은 시간 낭비입니다. – Zong

+0

calculateTotalPrice() 함수 내부 for 루프는 i가 naNumber.length (naNumber.length = 100)보다 작아 질 때까지 루프를 반복합니다. 그러나 itemPrice 배열에는 9 개의 값만 들어 있습니다. 그래서 그 후 ArrayIndexOutOfBound 예외가 발생합니다. –

답변

0

다음 calculateTotalPrice 당신이 범위를 벗어났습니다 total += itemPrices[9];에 액세스하려는

빠른 해결책 : 당신의 while 추가 한 후 naNumber[nCount] = 0;

하지만, 사용자가 100 개 이상의 제품을 입력 한 경우 응용 프로그램에서 수행 할 작업을 고려해야합니다.

+0

이것은 절대적으로 완벽합니다. 고맙습니다 * 1,000,000 – user2836276

0

배열 itemPrices에는 9 개의 요소가 있습니다. 그래서 당신은 입력 (10)가 만들 것 때 다음과 같이 실행 찾습니다

total += itemPrices[10 - 1]; 

어레이는 10 위치에있는 요소를 보유하지 않습니다 즉 itemPrices [9]. 따라서 ArrayIndexOutOfBoundException

당신 문제 루프의 종료 후 naNumber[nCount] == 10;하고 있기 때문에
관련 문제