I need to create a program to print a supermarket receipt on Java. The program w
ID: 3865873 • Letter: I
Question
I need to create a program to print a supermarket receipt on Java. The program will read a text file containing first a number (integer) which denotes how many items there are in the file, then the items. The formatting is, first the number, then irregardless of how many products there will be a product name, price, then quantity, example as following:
2 //the number of items in the file
Eggs //product name
2.99 //price
2 //quantity or amount
Milk
3.99
1
Now, I know how to read the file and how to do the calculations and print the items, I just need to find a way to store all items in an array since they're different data types.
Then I will need to create a loop to print the item name, price, and quantity while storing the price of each item times the quantity in a subtotal variable. I also need to validate if each attribute (name, price, or quantity) are the correct data type.
Explanation / Answer
use array of objects
import java.util.*;
class Product
{
private String name;
private double price;
private int quantity;
public Product(String name,double price,int quantity)
{
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String toString()
{
return " Product Name : "+name + " Price : "+price+" Quantity : "+quantity;
}
}
class TestProduct
{
public static void main (String[] args)
{
Product[] mylist = new Product[10]; //array of objects,read number of products from first line of file
String name;
double price;
int quantity,n;
int i=0;
//read data from file and put in variables to create array of objects of class Product
Scanner fileInput = new Scanner(new File("product.txt"));
while (fileInput.hasNext())
{
name = fileInput.nextLine();
price = fileInput.nextDouble();
quantity = fileInput.nextInt();
mylist[i] = new Product(name,price,quantity);
i++;
}
n = 0;
for(i=0;i<n;i++)
{
System.out.println(mylist[i]);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.