A Java question. You are given a text file containing the contents of a shopping
ID: 3824325 • Letter: A
Question
A Java question. You are given a text file containing the contents of a shopping cart at a grocery store. The records consists of a item name (which can be any number of words) a price, and a quantity separated by one or more white spaces. The file has this format:
You are to complete the class called GroceryCart.
which will read the items and then print: the name, the price, the quantity, and the extended price. Extended price is the quantity * the price. Use printf to format the output so that it is displayed in columns. The column with the name will be 20 characters wide an left justified. Each of the numbers will 8 characters wide and right justified. Price and extended price should have 2 decimal places. After all items are processed, print the word Total:, a space, a $ and then the total value of all the items in the cart (with 2 decimal places). It will look like this:
--------------Here is a file that will be used . Copy it into your project------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
Declare that the main method throws an exception when the file is not found.
Here is a starter. You need to define te file name as shown
item Price quantity raman 0.50 5 whole wheat bread 2.48 1Explanation / Answer
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class GroceryCart
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
String fileName = "items.txt"; //SUB "items2.txt"
FileReader fr =new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String sCurrentLine;
br.readLine();
int sum=0;
while((sCurrentLine=br.readLine())!=null)
{
String[] words = sCurrentLine.split("\s+");
int i=0;
String x = "";
for(String w: words)
{
if(!(w.charAt(0)>='0'||w.charAt(0)<='9'))
x=x+w;
else
break;
i++;
}
float price= Float.parseFloat(words[i++]);
int quantity= Integer.parseInt( words[i]);
float total=price*quantity;
sum+=total;
System.out.printf("%-20s %8.2f %8d %8.2f", x,price,quantity,total);
}
System.out.printf("Total: $%.2f", sum);
if(br!=null)
br.close();
if(fr!=null)
fr.close();
//your code here
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.