101k views
5 votes
4) Create a text file (you can name it sales.txt) that contains in each line the daily sales of a company for a whole month. Then write a Java application that: asks the user for the name of the file, reads the total amount of sales, calculates the average daily sales and displays the total and average sales. (Note: Use an ArrayList to store the data).

User Geocar
by
8.1k points

1 Answer

3 votes

Answer:

Here's an example Java application that reads daily sales data from a text file, calculates the total and average sales, and displays the results:

import java.util.ArrayList;

import java.util.Scanner;

import java.io.File;

import java.io.FileNotFoundException;

public class SalesDemo {

public static void main(String[] args) {

// Ask the user for the name of the file

Scanner input = new Scanner(System.in);

System.out.print("Enter the name of the sales file: ");

String fileName = input.nextLine();

// Read the daily sales data from the file

ArrayList<Double> salesData = new ArrayList<>();

try {

Scanner fileInput = new Scanner(new File(fileName));

while (fileInput.hasNextDouble()) {

double dailySales = fileInput.nextDouble();

salesData.add(dailySales);

}

fileInput.close();

} catch (FileNotFoundException e) {

System.out.println("Error: File not found!");

System.exit(1);

}

// Calculate the total and average sales

double totalSales = 0.0;

for (double dailySales : salesData) {

totalSales += dailySales;

}

double averageSales = totalSales / salesData.size();

// Display the results

System.out.printf("Total sales: $%.2f\\", totalSales);

System.out.printf("Average daily sales: $%.2f\\", averageSales);

}

}

Assuming that the sales data is stored in a text file named "sales.txt" in the format of one daily sale per line, you can run this program and input "sales.txt" as the file name when prompted. The program will then calculate the total and average sales and display the results.

I hope this helps!

Step-by-step explanation:

User Wenbin Geng
by
7.7k points