我在这里有一个代码,我试图运行。我试图写一个循环,当我输入0时,它将停止提示我从我写的任务。出于某种原因,我只能三次输入问题的答案。由于某种原因,当程序返回项目编号时,打印输出的摘要是错误的。 Bellow(end)ill提供打印输出。我认为这与我的ShoppingBag类有关。提前谢谢!
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 输入Cost10.5 输入计数(使用0停止):2(此处应保持运行,因为没有输入0) 袋子包含5件物品零售成本= 52.5总成本= 55.649998成本
(应该说7项而不是5项)
答案 0 :(得分:1)
问题出在这里,你在每次迭代时打印行李(检查最后一次打印)。
这也是错误项目计数的问题。
该项目不可用,因为您尚未将其放入包中。
您可能希望在循环后打印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();
}
编辑:作为旁注,你的循环确实运行了,你只是认为它已经结束了,因为你看到了打印袋。循环本身没有停止,你只需要输入继续那里。