gpt4 book ai didi

Java - 试图在 CSV 的特定列中找到最大值

转载 作者:行者123 更新时间:2023-12-05 04:25:27 27 4
gpt4 key购买 nike

我试图在特定列中找到最大值,但到目前为止我的代码只在控制台上打印该列。我怎样才能只读完最后一列并找到最大值并打印找到最大值的整行?

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();
}

更新代码

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();
}
}
}

最佳答案

警告:下面显示的代码未经测试。


String line = null; 这行之后,添加一个变量来保存已找到的最大数字。


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

在您的 while 循环中,解析每个输入。

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

如果比以前存储的大,则将其存储在 largestSoFar 变量中。

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

并测试您是否有任何线条。在没有行的情况下,上面的代码会错误地将 MIN_VALUE 常量报告为最大值。


在高级 Java 中,我们可能会使用流作为替代方法。

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 >`.

在实际工作中,我会使用 Java 生态系统中可用的几个优秀库之一来读取和解析 CSV 文件。

关于Java - 试图在 CSV 的特定列中找到最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73268841/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com