[英]Using While Loop instead of a For Loop in Java to ask User Input
我写了这段代码:
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循环,以向用户询问商品的价格(输入double),直到哨兵值。 我怎样才能做到这一点? 我知道我已经设置了三个迭代,但是我想在没有预设迭代次数的地方修改代码。 任何帮助,将不胜感激。
您可以尝试以下方法:
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
,以更好地处理货币金额。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.