我的While循环有什么问题?

时间:2016-05-05 15:24:54

标签: java while-loop

我对Java很新,还在练习。我用用户定义的方法做了一个简单的练习。代码如下。当我运行代码时,似乎if语句(在while循环中)不起作用。代码忽略if语句并直接循环回来。例如像这样的输出(没有输入var响应的地方): 输入项目名称: 牛奶 输入牛奶价格: 1 输入此料品的数量: 2 更多物品? (Y / N) 输入项目名称:

import java.util.*;

public class TotalPrice {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
    double total = getTotal();
    print(total);
}
public static double getTotal()
{
    double total = 0;
    Boolean moreItems = true;
    String response;
    while(moreItems)
    {
        total += getItemPrice(getItemName());
        System.out.println("More items? (y/n)");
        response = in.nextLine();
        if(response.equalsIgnoreCase("n"))
        { moreItems = false;}


    }
    return total;
}
public static String getItemName()
{
    String name;
    System.out.println("Enter item name: ");
    name = in.nextLine();
    return name;
}
public static double getItemPrice(String value)
{
    double price = 0;
    try{
        System.out.println("Enter price for " + value + ":");
        price = in.nextDouble();
    }
    catch(Exception e)
    {
        System.out.println("Invalid data type entered.");
        e.printStackTrace();
    }
    int quantity = getItemQuantity();
    return quantity * price;
}

public static int getItemQuantity()
{
    System.out.println("Enter the quantity for this item: ");
    int quantity = in.nextInt();
    return quantity;
}
public static void print(double total)
{
    System.out.printf("The total for your grocery items is: $%5.2f, "
            + "thanks for shopping with us!\n\n", total);

}

}

0 个答案:

没有答案