Anstelle der berechneten Ausgabe bekomme ich eine "Null" ohne die tatsächliche Gesamtausgabe, die ich suche. Ich denke, es ist, weil Artikel nicht richtig definiert ist. Mißachtung shop.txt hat es nicht auf mein Problem betrifftCompiles, aber insgesamt wird nicht berechnet
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));
}
}
Item-Klasse
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;
}
}
Können Sie einige Tupel von "shop.txt" geben? –
Ich könnte es entfernen und es würde auf die gleiche Weise ausgeben. Es ist nicht notwendig, nur dort - einfach ignorieren –