我这里有一个代码正在尝试运行。我正在尝试编写一个循环,当我输入 0 时,它将停止提示我执行我编写的任务。由于某种原因,我只能输入问题答案三次。另外,由于某种原因,当程序返回项目编号时,打印输出的摘要是错误的。波纹管(结束)将提供打印输出。我认为这与我的 ShoppingBag 类(class)有关。提前致谢!
public class ShoppingBag
{
private int items;
private float totalRetailCost;
private float taxRate;
public ShoppingBag(float taxRate)
{
this.taxRate = taxRate;
items = 0;
totalRetailCost = 0.0f;
}
public void place(int numItems, float theCost)
{
items += numItems;
totalRetailCost += (numItems * theCost);
}
public int getItems()
{
return items;
}
public float getTotalRetailCost()
{
return totalRetailCost;
}
public float getTotalCost()
{
return totalRetailCost*(1+taxRate);
}
public String toString()
{
String result = "the bag contains " + items + " items";
result += "The retail cost of the items is = " +
totalRetailCost; return result += "The total cost = " +
getTotalCost();
}
}
<小时/>
import java.util.*;
public class MainClass
{
public static void main(String[] args)
{
Scanner conIn = new Scanner (System.in);
ShoppingBag sb = new ShoppingBag(0.06f);
int count = 0;
float cost = 0.0f;
System.out.print("Enter count (use 0 to stop): ");
count = conIn.nextInt();
while (count != 0)
{
System.out.print("Enter Cost");
cost = conIn.nextFloat();
sb.place(count, cost);
System.out.print("Enter count (use 0 to stop): ");
count = conIn.nextInt();
System.out.print(sb);
}
conIn.close();
}
}
打印出来
输入计数(使用 0 停止):5 输入成本10.5 输入 count (使用 0 停止): 2 (这里应该继续运行,因为没有输入 0) 该包包含 5 件元素元素的零售成本为 = 52.5 总成本 = 55.649998输入成本
(应该说 7 项而不是 5 项)
最佳答案
问题就在这里,你在每次迭代时打印袋子(检查最后一次打印)。
这也是项目计数错误的问题之一。
该元素不可用,因为您尚未将其放入包中。
您可能想在循环后打印 bag
对象,或者如果您想知道您的 bag 在输入中间包含什么
// After the loop
while (count != 0)
{
System.out.print("Enter Cost");
cost = conIn.nextFloat();
sb.place(count, cost);
System.out.print("Enter count (use 0 to stop): ");
count = conIn.nextInt();
}
System.out.print(sb);
// After you placed the object in the bag,
// If you want the user to know what he has after each insertation
while (count != 0)
{
System.out.print("Enter Cost");
cost = conIn.nextFloat();
sb.place(count, cost);
System.out.print(sb);
System.out.print("Enter count (use 0 to stop): ");
count = conIn.nextInt();
}
编辑:作为旁注,您的循环确实运行了,您只是认为它已经结束,因为您看到了袋子打印。循环本身并没有停止,您只需进行输入即可继续。
关于java - 我的 while 循环无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35606969/