我们刚开始在Java课程中学习数组,所以我遇到了问题。我想要倍增"数量"通过"成本"因此它将打印出总成本,但是现在它为totalCost打印出0。这是驱动程序:
import java.util.Scanner;
public class Problem2 {
public static void main(String[] args){
String purchase, date;
double quantity, cost;
Scanner myScanner = new Scanner (System.in);
System.out.println("How many different types of items are you purchasing?");
int answer = myScanner.nextInt();
myScanner.nextLine(); // pick up the enter key
Basket[] myBasket = new Basket[answer];
for(int j = 0; j < answer; j++) {
System.out.println("Please enter the item you purchased.");
purchase = myScanner.nextLine();
System.out.println("Please enter the date.");
date = myScanner.nextLine();
System.out.println("Please enter the quantity.");
quantity = myScanner.nextFloat();
System.out.println("Please enter the cost.");
cost = myScanner.nextFloat();
myScanner.nextLine(); // pick up the enter key
myBasket[j] = new Basket(purchase, date, quantity, cost);
}
for (int i = 0; i< answer; i++)
{
System.out.println(myBasket[i]);
}
}
}
这是篮子类:
import java.text.NumberFormat;
public class Basket {
private String purchase, date;
private double quantity, cost, totalCost;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
public Basket(String purchase, String date, double quantity, double cost)
{
this.purchase = purchase;
this.date = date;
this.quantity = quantity;
this.cost = cost;
}
public void Calculations()
{
totalCost = cost * quantity;
}
public String toString()
{
return "Purchase: " + purchase
+ "\nDate: " + date
+"\nQuantity: " + quantity
+"\nCost:" + fmt.format(totalCost);
}
}
答案 0 :(得分:0)
将Calculations();
添加到toString()
public String toString()
{
Calculations();
return "Purchase: " + purchase
+ "\nDate: " + date
+"\nQuantity: " + quantity
+"\nCost:" + fmt.format(totalCost);
}
或者由于计算方法是公开的,您可以使用myBasket[j].Calculations();
之后
myBasket[j] = new Basket(purchase, date, quantity, cost);
答案 1 :(得分:0)
如果要填充totalCost,可以在创建Baskets实例时调用Calculations方法:
myBasket[j] = new Basket(purchase, date, quantity, cost);
myBasket[j].Calculations();
现在计算总费用并将其保存在以后可以打印的立场变量中。
答案 2 :(得分:0)
在main()的最后一行之后,添加以下代码
float total=0.0;
for (int i = 0; i< answer; i++)
{
//System.out.println(myBasket[i]);
total+=myBasket[2]*myBasket[3];
}
System.out.println("total cost:"+total);
答案 3 :(得分:0)
您的“计算”方法未被调用。 我想在构造函数的最后一行调用它。
顺便说一下,java方法在方法名称的开头就是小写,最好用它的名字命名 - 例如“calculateTotalCost”