【问题标题】:Error with BigDecimal calculation regarding User Input关于用户输入的 BigDecimal 计算错误
【发布时间】:2011-08-05 15:16:09
【问题描述】:

我对我的任务有这个想法,我希望收银机系统在用户输入它的成本价格和所述项目的数量时计算项目的总数。

这似乎可行,但随后导致了我的主要问题 - 我想让用户在说 10 次交易后输入字母“T”,以找出当天的总收入。

我尝试在计算等中使用带有 BigDecimal 数学类的 for 循环。 我的计算中的“valueOf”一词有错误,Eclipse 一直试图将我的值更改为“long”,我很确定这是不对的。

我的解释并不令人惊奇,所以我会给你我写的代码,并将 cmets 放在我的错误所在的旁边..

 try{
    Scanner in = new Scanner (System.in);       
    String t = "T";
    int count;

    for (count = 1;count<=10;count++){
           System.out.println("\n\nValue of Item " + count + " :");
       BigDecimal itemPrice = in.nextBigDecimal();
       System.out.println("Quantity of item " + count + " :");
       BigDecimal itemQuantity = in.nextBigDecimal();
       BigDecimal itemTotal = (BigDecimal.valueOf(itemPrice).multiply // error here
                                  (BigDecimal.valueOf(itemQuantity))); // error here
           System.out.println("\nTotal for item(s): £" + itemTotal); 
       count++;

           while (t == "T"){
       BigDecimal amountOfItems = (BigDecimal.valueOf(itemTotal).divide // error here
                                      (BigDecimal.valueOf(itemQuantity))); // error here 
       BigDecimal totalTakings = (BigDecimal.valueOf(itemTotal).multiply // error here
                                     (BigDecimal.valueOf(amountOfItems))); // error here
       System.out.println("The Total Takings For Today is £" + totalTakings + " " );

     }
    }  
   }
  }
 }

就像我说的,Eclipse 用来显示错误的“红线”仅在我的 BigDecimal 计算中的“valueOf”字样下方。

任何帮助都会很棒,因为我正在撕扯我的头发!!!!

谢谢,

维尼。

【问题讨论】:

  • 注意:永远不要将 Java 字符串与 == 进行比较,因为字符串 不是 原语,它们是对象 - 因此 == 是引用比较,而不是相等比较.请改用.equals()(或.equalsIgnoreCase())方法,因为这将进行您期望的比较。

标签: java while-loop bigdecimal value-of


【解决方案1】:

没有方法BigDecimal.valueOf(BigDecimal)itemPriceitemQuantity 已经 BigDecimal 值 - 您不需要任何转换:

BigDecimal itemTotal = itemPrice.multiply(itemQuantity);

编辑:好的,以上解决了你的直接问题,但你也得到了:

while (t == "T")
{
    // Loop that never changes the value of t
}

这有两个问题:

  • 循环要么永远执行,要么根本不执行,要么一直持续到抛出异常,因为循环条件永远不会改变,因为你没有改变t 的值。我猜你在某个时候想要t = System.in.readLine()...
  • 你在这里比较两个字符串 references 而我怀疑你想比较他们的 values,例如

    while (t.equals("T"))
    

【讨论】:

  • 哦,哇,看起来不错——但是我造成了一个无限循环,它会自动削减总收入计算,我希望它只在用户输入“T”时发生......
  • @Vinnie:好的,这次我编辑了答案来解释代码中的另一个问题。但一般来说,最好坚持每个问题一个问题。
猜你喜欢
  • 1970-01-01
  • 2014-06-06
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多