2013-07-07 39 views
1

我寫這段代碼:使用While循環,而不是一個for循環的Java要求用戶輸入

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

你可以試試這個:

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這裏貨幣更好地處理款項。

相關問題