【发布时间】:2017-09-23 04:36:01
【问题描述】:
我正在编写非常简单的代码,它要求您输入您有多少钱以及您想购买哪些产品(一行)。然后该程序应该告诉您是否有足够的钱购买产品。此外,它应该打印价格最低的产品。
示例:
- 输入您拥有的金额:
100 输入您要购买的产品和每个产品的价值:
Apple 10和Orange 20-
代码输出:
you have enough moneythe lowest price is (Apple 10)
这段代码有两个问题
首先,当我试图阻止
scanner接受输入时,我应该输入“停止”作为输入。但是,在我的情况下,只有当我输入“停止”2 次时才会执行该操作。我不知道为什么。我需要确定最低产品价值并打印出来。我尝试了很多不同的方法,但没有一个对我有用。
这是我目前的代码:
Scanner input = new Scanner (System.in);
String productName="";
double totalPrice=0;
double productValue = 0;
System.out.println("How much money do you have? ");
double money = input.nextDouble();
System.out.println("please insert the items in the invoice (the name of product and its price): "
+ " insert \"stop\" as the name of the product to finish your input");
while (!(productName.equals("stop")) ){
if(input.hasNext()){ productName = input.next();}
if (input.hasNextDouble()){ productValue = input.nextDouble();}
totalPrice = totalPrice + productValue;
}
if (money > totalPrice ){
System.out.println("you have enough money");
} else {
System.out.println("you don't have enough money");
}
【问题讨论】:
-
请为您正在编程的语言添加标签。(这可能有助于您获得更多浏览量。)
-
你有一个“停止”的错误,因为像 .hasNext* 这样的方法是阻塞方法。第一次输入“stop”后,程序会被 hasNextDouble 方法阻止,直到您输入内容。
标签: java if-statement while-loop minimum