簡體   English   中英

我的while循環不會運行

[英]My while loop wont run

我在這里嘗試運行一個代碼。 我正在嘗試編寫一個循環,當我輸入0時它將停止提示我編寫的查詢。 由於某種原因,我只能輸入三個問題的答案。 同樣由於某種原因,當程序返回項目編號時,打印輸出的摘要錯誤。 波紋管(完)不能打印。 我認為這與我的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項)

問題出在這里,您在每次迭代時打印袋子(檢查最后一次打印)。 從某種程度上講,這也是項目計數錯誤的問題。 該物品不可購買,因為您尚未將其放入包中。 您可能希望在循環后打印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();
}

編輯:作為一個旁注,您的循環確實運行了,您只是以為結束了,因為您看到了袋子的印記。 循環本身並沒有停止,您只需要輸入一個內容就可以繼續。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM