【问题标题】:Desired output calculation wrong?期望的输出计算错误?
【发布时间】:2013-10-22 15:34:53
【问题描述】:

我已经编写了这个程序,但是在编译时遇到了一个逻辑错误。

我的输入是1, 2, 6, 10,用于选择产品,同时输出应该是

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

奇怪的是它给了我

Total items ordered: 3
Price of items ordered: $6611.00
Sales Tax: $429.715
Total amount due: $7040.715 

我的 for 循环条件或计算中是否存在错误,或者我的数组是否存在导致这种过度膨胀的输出?

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

【问题讨论】:

  • 你也不应该使用浮点数来赚钱,永远。我建议使用 BigDecimal 类来计算销售税,但可以使用整数数学来完成计算,将美元值表示为整数美分。浮点数只会带来麻烦。
  • 如果您将用户的选择存储在 ArrayList&lt;Integer&gt; 而不是数组中,也可能会更容易。您不必担心排除零,因为列表中的唯一项目是用户选择的项目,您可以处理超过 100 次购买。

标签: java arrays methods logic output


【解决方案1】:

naNumber 将包含从 1 到 9 的数字。这意味着您将在某些时候将商品价格乘以一些较大的数字,这就是为什么您会得到较大的总数。

我认为你想做的是

double itemTotal = itemPrices[naNumber[i] - 1];
nTotal += itemTotal;

没有将 itemPrices[i] 乘以 naNumber[i]

此外,您实际上并不需要将nTotal 传递给方法并在每个循环中初始化double。您可以在循环外声明一个字段:

double total = 0;

像这样在循环中使用它:

total += itemPrices[naNumber[i] - 1];

并在方法结束时返回。

所以你的方法看起来像这样:

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

【讨论】:

  • itemPrices[i] 是错误的。您正在使用循环索引来选择商品价格,而不是用户选择的商品。
  • 更接近。 itemPrices 从 0 开始,但 naNumbers 从 1 开始。
  • 啊,是的。已编辑。希望现在是:P。我需要安装一个 IDE :)
【解决方案2】:

这里有三个问题。

  • 您将标记值 10 放入用户选择的项目数组中。
  • 您使用循环索引而不是用户在计算价格时选择的数字。
  • 您将每件商品的价格乘以它的数量。所以用户购买了商品 6 中的 6 件。

在您的main 方法中,您需要将用户的输入读入另一个变量,如果它不是标记值,则仅将其插入到数组中。

在您的 calculateTotalPrice 方法中,您应该像这样计算单个订单项的价格:

double itemTotal = itemPrices[naNumber[i] - 1];

【讨论】:

  • 我已经编辑了我的代码以包含更新的循环控制变量,现在它提示我 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at grapefruitorderingarray.GrapefruitOrderingArray.calculateTotalPrice(GrapefruitOrderingArray.java:126) at grapefruitorderingarray.GrapefruitOrderingArray.main(GrapefruitOrderingArray.java:94) Java Result: 1
  • 您愿意进一步详细说明吗?如果没有OutOfBounds 错误,它现在将无法编译?
  • 那是因为您将标记值 10 放入了数组中。所以你有四个项目,1、2、6 和 10,它从位置 0、1、5 和 9 查找它们的价格,但 itemPrices[9] 不存在并抛出 ArrayIndexOutOfBoundsException。正如我上面所说,您需要将用户的输入读取到另一个变量中,并且仅将其插入到数组中如果它不是标记值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 2018-08-10
相关资源
最近更新 更多