164k views
5 votes
write a java program for the following and use comments to be able to follow the program. Write a program that will create a text file for Grocery list name and prices, name it GroceryList2.txt, shown below, Check if the file exist and throw exception.. Check the tab between the list names and their prices. GroceryList2.txt-Notepad Item Price Apple 1.99 Butter 2.99 Soap 1.0 Bananas 1.0 Milk 2.99 Dog_Food 5.99 Write another program that will read the grocery list with their prices, the grocery list should display as shown below, Check if the file exist use try and catch. Calculate the sum of all items in the list, add a tax price 7.0% (tax is standard will not change). Below is a sample run. Sample Run Item Price Apple 1.99 Butter 2.99 Soap 1.0 Bananas 1.0 Milk 2.99 Dog_Food 5.99 Total amount before tax is: $15.96 Amount after (7.0%) tax: will be $17.08

User Ajk
by
8.2k points

1 Answer

5 votes

Here's a Java program that creates and reads a grocery list file, calculates the total amount before and after tax:

```java

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class GroceryListProgram {

public static void main(String[] args) {

String fileName = "GroceryList2.txt";

// Create the grocery list file if it doesn't exist

File groceryListFile = new File(fileName);

if (!groceryListFile.exists()) {

try {

groceryListFile.createNewFile();

System.out.println("Created a new grocery list file: " + fileName);

} catch (Exception e) {

System.out.println("Error creating grocery list file.");

e.printStackTrace();

}

} else {

System.out.println("Grocery list file already exists: " + fileName);

}

System.out.println("Grocery List:");

// Read and display the grocery list with prices

try {

Scanner scanner = new Scanner(groceryListFile);

double totalAmount = 0.0;

while (scanner.hasNextLine()) {

String line = scanner.nextLine();

String[] parts = line.split("\t");

if (parts.length == 2) {

String item = parts[0];

double price = Double.parseDouble(parts[1]);

System.out.println(item + "\t$" + price);

totalAmount += price;

}

}

scanner.close();

System.out.println("Total amount before tax is: $" + totalAmount);

double taxAmount = totalAmount * 0.07;

double totalAmountAfterTax = totalAmount + taxAmount;

System.out.println("Amount after (7.0%) tax: $" + totalAmountAfterTax);

} catch (FileNotFoundException e) {

System.out.println("Grocery list file not found.");

e.printStackTrace();

}

}

}

```

Make sure to place the "GroceryList2.txt" file in the same directory as the Java program. The program will create the file if it doesn't exist and then read the items and prices from the file, calculating the total amount before and after tax.

User Marc Frame
by
7.9k points