运行时错误

时间:2013-07-03 16:06:34

标签: java runtime-error

我正在编写一个模拟商店的程序。问题是,当我试图获得总数时,它只给出了我购买的最后一件商品的总数,而不是购买的所有商品。我做错了什么,我能解决什么?

 import java.util.Scanner;

public class Invoice {

public static String partNum;
public String description;
public int quantity;
public double price;


    public String part_description(String parts){
                partNum=parts;

                if(parts.equals("10")){
                    description="This is a large metal hammer, $20";price=20;}
                else if(parts.equals("15")){description="This is a small plastic hammer, $5";price= 5;}
                else if(parts.equals("20")){description="This is a medium wooden hammer, $10";price=10;}
                else if(parts.equals("25")){description="This is a bucket of paint, $25";price=25;}
                else{description="No such part number exists.";}
                return description; 
    }
    public void setquantity(int amount){
        quantity=amount;

    }
    public int getquantity(){

        return quantity;
    }
    public void setprice(double cost){
        price=cost;
        if(cost<0){cost=0;}

    }
    public double getprice(){
        return price;
    }
    public double getInvoiceAmount(double total){
        total=total+(quantity*price);
        return total;
    }

    public static void main(String[] args){

        Scanner s1= new Scanner(System.in);
        Invoice invoiceObject= new Invoice();
        boolean ask=true;
        while(ask==true){


        System.out.println("Chose one of the fallowing part numbers: 10, 15, 20, 25");

         partNum=s1.nextLine();

        System.out.println(invoiceObject.part_description(partNum));

        System.out.printf("\nHow many #%s would you like to get: ", partNum);
        int numOf=s1.nextInt();
        invoiceObject.setquantity(numOf);



        System.out.println("would you like to keep shopping? chose true or false");
        ask=s1.nextBoolean();
        partNum=s1.nextLine();


        }



        System.out.println("Your total price will be:$ "+invoiceObject.getInvoiceAmount(0));




}}

1 个答案:

答案 0 :(得分:0)

你从未在任何地方实际加总价格。你需要有一个变量,如totalSum。您希望在用户开始执行任何操作之前将其设置为0。然后你想增加价格。

//pseudo code.
totalSum = totalSum + (quantity*price)

//at the end
print(totalSum)