而不是计算的输出,我得到一个" null"没有我想要的实际总打印输出。我之所以这么认为是因为项目没有得到恰当的定义。无视shop.txt,它对我的问题没有影响
package Shopping;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.NumberFormat;
public class Shop
{
public static void main(String[] args)
{
//I/O stream
String fileName = "shop.txt";
Scanner inputStream = null;
System.out.println("The file " + fileName +
"\ncontains the following lines:\n");
try
{
inputStream = new Scanner(new File(fileName));
}
catch (FileNotFoundException e)
{
System.out.println("This is a shopping list " +
fileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine();
System.out.println(line);
}
inputStream.close();
ArrayList<Item> Cart = new ArrayList<Item>();
Item item;
String itemName;
double itemPrice;
int quantity;
double totalPrice = 0.0;
double sum = 0.0;
int priority;
Scanner scan = new Scanner(System.in);
String continueShopping = "y";
do
{
System.out.print("Enter the name of the item: ");
itemName = scan.nextLine();
System.out.print("Enter the unit price: ");
itemPrice = scan.nextDouble();
System.out.print("Enter the quantity: ");
quantity = scan.nextInt();
// create a new item and add it to the cart
item = new Item(itemName, itemPrice, quantity);
Cart.add(item);
for (int i = 0; i < Cart.size(); i++)
{
Item itm = Cart.get(i);
System.out.println(itm);
}
// Print out the results
System.out.print("Continue shopping (y/n)? ");
scan.nextLine();
continueShopping = scan.nextLine();
}
while (continueShopping.equals("y"));
for (int i = 0; i < Cart.size(); i++)
{
Item itm = Cart.get(i);
System.out.println(itm);
totalPrice = itm.getQuantity() * itm.getPrice();
sum += totalPrice;
}
NumberFormat type = NumberFormat.getCurrencyInstance();
System.out.println("The total price is: " + type.format(sum));
}
}
项目类
package Shopping;
import java.text.NumberFormat;
public class Item
{
private String name;
private double price;
private int quantity;
public Item(String itemName, double itemPrice, int quantity2)
{
}
public void Item(String itemName, double itemPrice, int numPurchased)
{
name = itemName;
price = itemPrice;
quantity = numPurchased;
}
//Info about the item
public String toString()
{
NumberFormat type = NumberFormat.getCurrencyInstance();
return (name + "\t" + type.format(price) + "\t" + quantity + "\t"
+ type.format(price * quantity));
}
//Retrieve the item price
public double getPrice()
{
return price;
}
//Retrieve item name
public String getName()
{
return name;
}
//Retrieve quantity
public int getQuantity()
{
return quantity;
}
}
答案 0 :(得分:2)
您的Item
类有一个空构造函数
public Item(String itemName, double itemPrice, int quantity2) {
}
以及名为Item
public void Item (String itemName, double itemPrice, int numPurchased)
{
name = itemName;
price = itemPrice;
quantity = numPurchased;
}
删除空构造函数并从方法中删除返回类型void
,将其转换为构造函数。