To calculate the minimum, maximum, and average of a list of numbers in Java and write the results to a text file, you can use the Collections.min
and Collections.max
methods to find the minimum and maximum values, and use a loop to calculate the average. Here's an example of how you might do this:
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); int min = Collections.min(numbers); int max = Collections.max(numbers); int sum = 0; for (int number : numbers) { sum += number; } double average = (double) sum / numbers.size(); try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) { writer.write("Min: " + min); writer.newLine(); writer.write("Max: " + max); writer.newLine(); writer.write("Average: " + average); } catch (IOException e) { e.printStackTrace(); } } }Sourcl.www:eautturi.com
This code will calculate the minimum, maximum, and average of the list of numbers and write the results to the file output.txt
. The resulting file will contain the following text:
Min: 1 Max: 10 Average: 5.5