1

我写了这段代码:

Scanner askPrice = new Scanner(System.in);

for(double i = 0 ; i < 3; i++);
{
double totalInitial = 0.00;
System.out.println("Enter the price for your item. "
+ "Press enter after each entry. Do not type the '$' sign: ") ;
double price1 = askPrice.nextDouble(); //enter price one
double price2 = askPrice.nextDouble(); //enter price two
double price3 = askPrice.nextDouble(); //enter price three

double total = ((totalInitial) + (price1) + (price2) + (price3));

我想将 for 循环更改为 while 循环,以询问用户一个项目的价格(双精度输入),直到一个哨兵值。我怎样才能做到这一点?我知道我已经设置了三个迭代,但是我想修改没有预设迭代次数的代码。任何帮助,将不胜感激。

4

1 回答 1

1

你可以试试这个:

Scanner askPrice = new Scanner(System.in);
// we initialize a fist BigDecimal at 0
BigDecimal totalPrice = new BigDecimal("0");
// infinite loop...
while (true) {
    // ...wherein we query the user
    System.out.println("Enter the price for your item. "
        + "Press enter after each entry. Do not type the '$' sign: ") ;
    // ... attempt to get the next double typed by user 
    // and add it to the total
    try {
        double price = askPrice.nextDouble();
            // here's a good place to add an "if" statement to check 
            // the value of user's input (and break if necessary) 
            // - incorrect inputs are handled in the "catch" statement though
        totalPrice = totalPrice.add(new BigDecimal(String.valueOf(price)));
            // here's a good place to add an "if" statement to check
            // the total and break if necessary
    }
    // ... until broken by an unexpected input, or any other exception
    catch (Throwable t) {
            // you should probably react differently according to the 
            // Exception thrown
        System.out.println("finished - TODO handle single exceptions");
            // this breaks the infinite loop
        break;
    }
}
// printing out final result
System.out.println(totalPrice.toString());

请注意BigDecimal此处以更好地处理货币金额。

于 2013-07-07T16:02:04.577 回答