【问题标题】:Using While Loop instead of a For Loop in Java to ask User Input在 Java 中使用 While 循环而不是 For 循环来询问用户输入
【发布时间】:2013-07-05 00:30:37
【问题描述】:
我写了这段代码:
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 循环,以询问用户一个项目的价格(双精度输入),直到一个标记值。我怎样才能做到这一点?我知道我已经设置了三个迭代,但是我想修改没有预设迭代次数的代码。任何帮助将不胜感激。
【问题讨论】:
标签:
java
for-loop
while-loop
iteration
【解决方案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,以便更好地处理货币金额。