使用While循环而不是Java中的For循环来询问用户输入

时间:2013-07-07 15:54:31

标签: java for-loop while-loop iteration

我写了这段代码:

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循环,以便向用户询问项目的价格(双精度输入),直到一个标记值。我怎样才能做到这一点?我知道我已经设置了三个迭代,但我想修改没有预设迭代次数的代码。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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以更好地处理货币总和。