简体   繁体   中英

Using While Loop instead of a For Loop in Java to ask User Input

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM