Я хочу, чтобы файл Cart.txt мог записывать независимо от того, какие продажи были в самом файле.Файл сейчас просто говорит:
3,2,Shoes
3,4,Shirt
2,5,Car
Это текущий вывод:
run:
Enter how many items you are buying
3
Enter the items you are buying, structured as followed
Quantity,Price,Item Name:
3,2,Shoes
3,4,Shirt
2,5,Car
Those values were written to Cart.txt
Sold 3 of Shoes at $2.00 each.
Sold 3 of Shirt at $4.00 each.
Sold 2 of Car at $5.00 each.
Total sales: $28.00
Это сам код:
package shop;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class Shop
{
public static void main(String[] args)
{
String fileName = "Cart.txt";
PrintWriter outputStream = null;
try
{
outputStream= new PrintWriter (fileName);
}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file "+ fileName);
System.exit(0);
}
System.out.println("Enter how many items you are buying");
Scanner keyboard = new Scanner (System.in);
Scanner intinput = new Scanner (System.in);
int input = intinput.nextInt();
System.out.println("Enter the items you are buying, structured as followed"
+ " \nQuantity,Price,Item Name:");
for(int count=1; count<=input; count++)
{
String line = keyboard.nextLine();
outputStream.println(line);
}
outputStream.close();
System.out.println("Those values were written to "+ fileName);
try
{
Scanner inputStream = new Scanner(new File(fileName));
String line = inputStream.toString();
double total = 0;
for(int count=1; count<=input; count++)
{
line = inputStream.nextLine();
String[] ary = line.split (",");
int quantity = Integer.parseInt (ary[0]);
double price = Double.parseDouble(ary[1]);
String description = ary[2];
System.out.printf("Sold %d of %s at $%1.2f each. \n",
quantity, description, price);
total += quantity * price;
}
System.out.printf("Total sales: $%1.2f\n", total);
inputStream.close();
}
catch (FileNotFoundException e)
{
System.out.println("Cannot find file " + fileName);
}
catch (IOException e)
{
System.out.println("Problem with input file " + fileName);
}
}
}