Find out the min, max, total of an input text file and write it into a new output text file?

java program to find maximum and minimum number in a file
max and min value of integer in java
package file_handling;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;

public class WriteToFile {
public static void main(String[] args) {

      int currentNumber, sum = 0, numberCount=0;
      FileReader infile; 

      Scanner input = new Scanner(System.in);
      File file2 = new File("D:/test1.txt");
      input = new Scanner(file2);
        int min;
        int max;
      while (input.hasNextInt()){
        currentNumber = input.nextInt();
        sum+=currentNumber;

        numberCount++;
        if(currentNumber < min) {
            min= currentNumber;
        }
        if(currentNumber > max) {
            max = currentNumber; 
        }
      }

      System.out.println("Min: " + min);

      System.out.println("Max: " + max);

      System.out.println("Total: " + sum);

    File file1 = new File("D:/test.txt");
    try {
        PrintWriter output = new PrintWriter(file1);
        output.write(max, min, sum);
        output.close(); //don't forget this method 
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }

}

}

input.txt:

9.22

11.55

-2.21

16.95

22.11

-5.11

Based on the content of input.txt, I'm trying to write a program to find out the maximum number, the minimum number and the total of those numbers and write the results into a file named output.txt file.

output.txt:

Min:

Max:

Total:

I have to use the Scanner class to read from the file and the PrintWriter class to write out to the file.

I'm not sure what I'm doing wrong, could someone help me please?

I get this error at line 44: output.write(max, min, sum); Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method write(char[], int, int) in the type PrintWriter is not applicable for the arguments (int, int, int)

at file_handling.WriteToFile.main(WriteToFile.java:44)


There are a couple of issues :

  1. Your code won't compile as there is no method of PrintWriter that takes in (int, int, int). You can use the method write(String s) to achieve the same.

    output.write(String.valueOf("Min: " + min + "\n\nMax: " + max + "\n\nTotal : " + sum));
    
  2. The file is read as a sequence of bytes, so you'll need to use input.hasNextLine() to read each line. With your current code, your while loop is not executed. Next you will need to convert each String to Double. So your while-loop needs to tweaked to as below :

    while (input.hasNextLine()) {
        String currLine = input.nextLine(); 
    
        // check for empty spaces
        if (currLine != null && currLine.trim().length() > 0) {
            currentNumber = Double.parseDouble(currLine); 
    
            // same from here
            sum += currentNumber;
            numberCount++;
            if (currentNumber < min) {
                min = currentNumber;
            }
            if (currentNumber > max) {
                max = currentNumber;
            }       
        }
    }
    
  3. You cant use int to store double values. So declare all your int to double. (Also not sure why you are using numberCount, it can be removed.)

    double currentNumber, sum = 0, numberCount = 0, min = 0, max = 0;
    

Solved: Write Code To Read The Content Of The Text File In , For Each Line In Input.txt, Write A New Line In The New Text File Output.txt If The Input.txt Has The Following: Min: 1,2,3,5,6 Max: 1,2,3,5,6 Avg: 1,2,3,5,6 Your THE OPERATION VARIABLE TO DETERMINE THE OUTPUT TO WRITE. Sum: 1,2,3,5,6 P70: 1,2,3 ○ Your output.txt should read: The min of [1,2,3,5,6] is 1. Find largest number in a text file with java. GitHub Gist: instantly share code, notes, and snippets.


Use printf instead of write:

output.printf("Max:  %d\n", max);
output.printf("Min:  %d\n", min);
output.printf("Total:  %d\n", sum);

Reading from files, To set up a Scanner to read from a text file, we instead use the syntax. Scanner input = new Scanner(new File("numbers.txt")); tell the exception object to print some additional details about what went wrong to the output pane. The first step in being able to do this is to write a program that can determine what the smallest  Write a function called MAXMIN with (input) parameter FileName and an integer Count, and return a return average of MAX and MIN: 1) Open an existing file FileName. You need to use standard ways to check if the file exists. There are a number of integers in this file. Each integer takes one line. 2) Read from the file, one integer at a time 3


If you can use Java 8 or Java 9 you could write way shorter and simpler code:

  public static void main(String[] args) throws IOException {
    DoubleSummaryStatistics statistics = Files
      .lines(new File("./test1.txt").toPath())
      .filter(l -> !l.isEmpty())
      .mapToDouble(Double::parseDouble)
      .summaryStatistics();

    double min = statistics.getMin();
    System.out.println("Min: " + min);
    double max = statistics.getMax();
    System.out.println("Max: " + max);
    double sum = statistics.getSum();
    System.out.println("Total: " + sum);

    Files.write(new File("./test2.txt").toPath(), List.of(Double.toString(min), Double.toString(max), Double.toString(sum)));
  }

The nio-API defines classes and methods to works with files which also handles the closing of files (resources).

The Stream-API has classes and methods to process elements. To compute the sum, max and min values for a stream of doubles (DoubleStream) we can use the method DoubleStream.summaryStatistics().

If you cannot use Java 9 use Arrays.asList() instead of List.of()

NASA Tech Briefs, array subprograms (MAX, MIN, PROD, SUM, GET, and PUT), numerical linear-​algebra subprograms, Runge–Kutta integrators, and three text input/output families of software packages. In All are designed to facilitate writing new software in Ada. The SOUrce COGe is available as ASCII text files on two 360K​, 5.25-in. Based on the content of input.txt, I'm trying to write a program to find out the maximum number, the minimum number and the total of those numbers and write the results into a file named output.txt file. output.txt: Min: Max: Total: I have to use the Scanner class to read from the file and the PrintWriter class to write out to the file.


New Perspectives on XML, Comprehensive, He wants your help in converting this file to an XML document. Using your text editor, open the boisetxt.xsl and readtabtxt.xsl files from the xml08 Below the output element, declare the tempDataset variable, importing the text from the value of the dataValues parameter by using the XPath 2.0 max() and min() functions. Hi I have to find the minimum and maximum number from the input file and output it on another file.


For each line in input.txt , write a new line in the new text file output , I have to make a output.txt file based on a input.txt The input input.txt reads sum​:1,2,3,5,6 min:1,5,6,14,24 max:2,3,9 P70:1,2,3 output file should read The min of [​1, 2, 3, 5, 6] is 1. to help you on your way with one option try this. of information once you get familiar with it # the example works with the  “The ‘MAX’ and ‘MIN’ functions in and of themselves find the maximum or minimum value in the range of cells selected” Kasper Langmann , Co-founder of Spreadsheeto So whether we select a literal list of values like ‘=MAX(1,2,3,4,5)’ or a range of cell references containing values like ‘=MAX(A2:A6)’, the outcome is the same


[PDF] Input Files, write files. – Called input/output (I/O). • Reading a file is very similar to reading input from the command line! File object to get info about a file Scanner input = new Scanner(new File("mydata.txt")); Try to compile your completed FileInputTest.java program. You will print the max, min, sum, count, and average of the. I'd factor out the algorithm into a function, unfortunately you can't use std::minmax_element as this only works for ForwardIterator, but you can write your own algorithm for InputIterator easily enough.