Write a Java program that will record the purchases made at a store. For each pu
ID: 3817116 • Letter: W
Question
Write a Java program that will record the purchases made at a store. For each purchase, read from the keyboard an item’s name, its price, and the number bought. Compute the cost of the purchase (number bought times price), and write all this data to a text file. Also, display this information and the current total cost on the screen. After all items have been entered, write the total cost to both the screen and the file. Since we want to remember all purchases made, you should append new data to the end of the file.
Explanation / Answer
Hello,
I have given the code below.
import java.util.*;
import java.io.*;
class StoreItems
{
String itemname;
int price;
int number;
int x;
void insertrecord()
{
int total=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter No. of total Items");
x=s.nextInt();
for(int i=0;i<x;i++)
{
System.out.println("Enter Item name:");
String itemname= s.next();
System.out.println("Enter price:");
int price=s.nextInt();
System.out.println("Enter number of "+itemname+" bought:");
int number=s.nextInt();
total=total+number*price;
try{
File f1 = new File("info.txt");
if(!f1.exists()) {
f1.createNewFile();
}
FileWriter fileWritter = new FileWriter(f1.getName(),true);
BufferedWriter bw = new BufferedWriter(fileWritter);
bw.write(itemname);
bw.write(price);
bw.write(number);
bw.write(total);
bw.close();
System.out.println("Data inserted to file!!!");
}
catch(IOException e){
e.printStackTrace();
}
finally
{
System.out.println("Total Price:"+total);
}
}
}
}
public class Stores
{
public static void main(String[] args)
{StoreItems obj=new StoreItems();
obj.insertrecord();
}}
If there's further any problem or query feel free to ask anytime.
Thank You for using Chegg!!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.