Using While Loop instead of a For Loop in Java to

2019-08-13 15:28发布

问题:

I wrote this piece of code:

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

I want to change the for loop to a while loop to ask the user a price for an item (input of a double) until a sentinel value. How can I do this? I know I have three iterations already set, but I want to modify the code where there is not a preset number of iterations. Any help would be appreciated.

回答1:

You could try this:

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());

Note the BigDecimal here to better handle sums of currency.