我正在尝试从数据文件中查找一行文本的最大值和最小值。尽管此数据文件中有大量文本行。
数据
-99 1 2 3 4 5 6 7 8 9 10 12345
10 9 8 7 6 5 4 3 2 1 -99
10 20 30 40 50 -11818 40 30 20 10
32767
255 255
9 10 -88 100 -555 1000
10 10 10 11 456
-111 1 2 3 9 11 20 30
9 8 7 6 5 4 3 2 0 -2 -989
12 15 18 21 23 1000
250 19 17 15 13 11 10 9 6 3 2 1 -455
9 10 -8 10000 -5000 1000
我尝试过将线条转换为数组,这让我有所收获。
这是我的代码
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
// It is called "Average". Don't mind that.
public class Average
{
public static void main(String[] args) throws IOException
{
Scanner file = new Scanner(new File("average.dat"));
String[] array = null;
while(file.hasNextLine())
{
//Storing the ints from the data file into an array.
String line = file.nextLine();
String[] str = line.split("\\s+");
array = new String[str.length];
for (int i = 0; i < str.length; i++){
array[i] = (str[i]);
}
System.out.println("Max:" + Average.getMax(array));
System.out.println("Min:" + Average.getMin(array));
System.out.println();
}
}
//Simple way of getting max value. Nabbed it off google.
public static String getMax(String[] inputArray)
{
String maxValue = inputArray[0];
for(int i=1;i < inputArray.length;i++){
if(inputArray[i].compareTo(maxValue)>0){
maxValue = inputArray[i];
}
}
return maxValue;
}
//Simple way of getting min value. Took off google as well.
public static String getMin(String[] inputArray){
String minValue = inputArray[0];
for(int i=1;i<inputArray.length;i++){
if(inputArray[i].compareTo(minValue)<0){
minValue = inputArray[i];
}
}
return minValue;
}
}
这是我的输出
Max:9
Min:-99
Max:9
Min:-99
Max:50
Min:-11818
Max:32767
Min:32767
Max:255
Min:255
Max:9
Min:-555
Max:456
Min:10
Max:9
Min:-111
Max:9
Min:-2
Max:23
Min:1000
Max:9
Min:-455
Max:9
Min:-5000
如您所见,最小值是正确的。但是,最大值不是吗?它无缘无故地给我9分,我不知道为什么。您可能会问“为什么不直接将数组设为 int[] 而不是 String[]?”我不知道如何将数据文件中的整数复制到整数数组中。我只知道如何使用字符串数组来做到这一点。有谁知道正确的方法吗?
最佳答案
带有注释和解释的紧凑解决方案:
public static void main(String[] args) {
// Create an input stream
try (Stream<String> stream = Files.lines(Paths.get("average.dat"))) {
// Get each line from the stream
stream.forEach(line -> {
// Cut the line into peaces
String[] numbers = line.split(" ");
// Create a list of integers from the pieces
List<Integer> integers = Arrays.stream(numbers).map(Integer::parseInt).collect(Collectors.toList());
// Calculate max
System.out.println("Max:" + integers.stream().flatMapToInt(IntStream::of).max().orElseThrow());
// Calculate min
System.out.println("Min:" + integers.stream().flatMapToInt(IntStream::of).min().orElseThrow());
// Ouput a new line
System.out.println();
});
} catch (IOException e) {
e.printStackTrace();
}
关于java - 从数据文件中的一行整数中查找最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61689419/