Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need to write a program that opens file for reading and writing, as well as as

ID: 3771955 • Letter: I

Question

I need to write a program that opens file for reading and writing, as well as as handle exceptions. The file Grocery.txt contains the list of grocery that print out in a grocery store. Write a program read in the Grocery.txt file, calculate the total and also print out an exception for non-digit price, and save the output to a different file.

Example for only two input from Grocery.txt:

Kraft Ranch Dressing - 16 oz,2.99

Folgers Classic Roast Coffee - 39 oz,8.55

Output file:

16 oz Kraft Ranch Dressing: $2.99

39 oz Folgers Classic Roast Coffee: $8.55

Total: $11.54

Explanation / Answer

Grocery.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Grocery {

   public static void main(String[] args) throws IOException {
       // TODO Auto-generated method stub
       List<String> items = new ArrayList<String>();
       List<String> quantity = new ArrayList<String>();
       List<String> price = new ArrayList<String>();
       String item[];
       String pquan[];
       double total=0;
File input = new File("Grocery.txt");
Scanner scnr = new Scanner(input);
int i =0;
try{
while(scnr.hasNextLine()){
String line = scnr.nextLine();
item =line.split("-");
items.add(item[0]);
pquan =item[1].split(",");
quantity.add(pquan[0]);
total+=Double.parseDouble(pquan[1]);
price.add("$"+pquan[1]);
i++;
}
}
catch(Exception e){
   System.out.println("Non-digit price is entered");
   return;
}
String data="";
for(int j =0;j<i;j++){
   data+=quantity.get(j)+" "+items.get(j)+" :"+price.get(j)+" ";
}
DecimalFormat deci = new DecimalFormat("#.00");

data+="Total :$"+deci.format(total);
FileWriter writer = new FileWriter("output.txt", false);
writer.write(data);
writer.flush();
writer.close();

   }

}

Grocery.txt file:

Kraft Ranch Dressing - 16 oz,2.99
Folgers Classic Roast Coffee - 39 oz,8.55

Output:

16 oz Kraft Ranch Dressing :$2.99
39 oz Folgers Classic Roast Coffee :$8.55
Total :$11.54