3

I was trying to find the largest value in a specific column but so far my code only prints that column on the console. How can I read through the last column only and find the largest value and print that entire row where the largest number is found?

BufferedReader csvReader = null;
try {
    csvReader = new BufferedReader(new FileReader(selectedFile.getAbsolutePath()+"\\FinalResults.csv"));
} catch (FileNotFoundException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
String line = null;
try {
    while ((line = csvReader.readLine()) != null) {
        String[] cols = line.split(",");
        System.out.println("Coulmn 3= " + cols[2]);
    }
} catch (IOException e) {
    e.printStackTrace();
}   

Updated Code

int largestSoFar = Integer.MIN_VALUE ;
BufferedReader csvReader = null;
            try {
                csvReader = new BufferedReader(new FileReader(selectedFile.getAbsolutePath()+"\\FinalResults.csv"));
                System.out.println(selectedFile.getAbsolutePath()+"\\FinalResults.csv");
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            String line = null;
            try {
                while ((line = csvReader.readLine()) != null) {
                    String[] cols = line.split(",");
                    
                    int number = Integer.parseInt( cols[2] ) ;
                    if ( number > largestSoFar ) { largestSoFar = number ; }
                 
                  //  calculateMinAndMax(cols[2]); 
                    System.out.println(number);
                  //  System.out.println("Coulmn 3= " + cols[2]);
                }
            } catch (IOException e) {

                e.printStackTrace();
            }   
            }
        }
  • 3
    Well, how do you find a maximum value in general? You already know how to read the value you are looking for. Hint: all you need to do is to store the line with the greatest value you've seen so far, and print it after the loop. – Hulk Aug 07 '22 at 15:52
  • 2
    By the way, it's bad practice to print the stack trace and continue regardless after catching an exception. What is the point of calling `csvReader.readLine()` if you've just caught `FileNotFoundException`? It would be better to let the exception come out of your method. Just add `throws IOException` to your method signature. – k314159 Aug 07 '22 at 15:55
  • Now that you have the value from the last column, it's a matter of learning how to compute the max using a loop. – Cheng Thao Aug 07 '22 at 16:35
  • @Cheng Thao, I updated my code, is there a way I can retrieve the entire row associated with that largest number in the column? – user19693987 Aug 07 '22 at 17:09
  • @k314159 oh that makes sense, thank you for pointing it out, will correct. :) – user19693987 Aug 07 '22 at 17:10
  • @user19693987 yes. It works the same way you compute the max. Use a string variable to track the line with the largest value. – Cheng Thao Aug 07 '22 at 17:14
  • @ChengThao any examples on how that would look like? – user19693987 Aug 07 '22 at 17:19

1 Answers1

2

Caveat: code shown below is untested.


After your line String line = null;, add a variable to hold the largest number yet found.

…
String line = null;
int largestSoFar = Integer.MIN_VALUE ;

Inside your while loop, parse each input.

int number = Integer.parseInt( cols[2] ) ;

If larger than previously stored, store it in the largestSoFar variable.

if ( number > largestSoFar ) { largestSoFar = number ; }

And test that you have any lines. In the case of no lines, the code above would erroneously report the MIN_VALUE constant as the largest value.


In advanced Java, we might use streams as an alternative approach.

Optional< Integer > result =                            // An `Optional` object may be empty. For example, if the file contains no lines, no largest number exists, so an empty `Optional` would represent that fact. 
    Files                                               // From Java NIO.2, the modern way to handle files.
        .lines( myPath )                                // Make a stream whose elements are each line of text read from file.
        .map( line -> line.split( myDelimiter )[ 2 ] )  // Make a new stream whose elements are the third field of each line.
        .map( thirdField -> Integer :: valueOf )        // Make a new stream whose elements are `Integer` objects parsed from third field text.
        .max() ;                                        // Track the largest `Integer` object, returned wrapped as an `Optional< Integer >`. 

In real work, I would use one of the several excellent libraries available in the Java ecosystem to read and parse a CSV file.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • I updated my code above but I seem to get an error as such - Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1.0" – user19693987 Aug 07 '22 at 16:49
  • I also want to get the entire row not just the column value. – user19693987 Aug 07 '22 at 16:55
  • I should mention my CSV has a string in the first column and is followed by an int column and a float column. – user19693987 Aug 07 '22 at 17:04
  • Realized the issue and changed int to float. but I'd still like to know how the retrieve the entire row that has that largest number. – user19693987 Aug 07 '22 at 17:07
  • @user19693987 You have the entire row there in your hand: `String[] cols`. Perhaps you should define a [record](https://openjdk.org/jeps/395) and add them to a collection like a `Set` or `List`. Do some searching of Stack Overflow, as this has been addressed countless times. And study *The Java Tutorials* provided by Oracle Corp free of cost. – Basil Bourque Aug 07 '22 at 17:41