java - 从文本文件中查找最大值

标签 java arrays file search logic

我一直在努力提高我的 Java 技能,但在某些方面仍然遇到问题。对于这个程序,除了我的最终输出之外,一切似乎都正常运行。本质上,一旦它读入numbers.txt,它就应该将这些值放入一个数组中,然后打印出最大的数字。然而,我的逻辑一定有缺陷,因为目前它只输出列表中的顶部数字,而不是找到最大的数字。这是我的程序,我在我认为我的逻辑有缺陷的地方发表了评论。

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ProcessDataFile {

    public static void main(String[] args) throws IOException {

        String fileName = "numbers.txt";
        String temp;
        int max = Integer.MIN_VALUE;
        int i = 0;
        int[] numbers = new int[100000];

        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            while ((temp = br.readLine()) != null) {
                if (temp.isEmpty())
                    break;
                numbers[i++] = Integer.parseInt(temp);
            }
        }
        // I think my logic error is somewhere in this section. 
        for (i = 0; i < numbers.length; i++)
            if (max < numbers[i])
                max = numbers[i];



        System.out.println("The largest number is: " + max);
    }
}

最佳答案

是的,有一个错误,但不在你的逻辑中,以前缺少 for 括号,所以只是 for 之后的第一行在迭代内。使用正确的标识查看您的代码

// I think my logic error is somewhere in this section. 
for (i = 0; i < numbers.length; i++)
    if (max < numbers[i])

max = numbers[i]; // this line is out of the for scope!!!

只需添加 {} 即可定义循环范围

// I think my logic error is somewhere in this section. 
for (i = 0; i < numbers.length; i++){
    if (max < numbers[i])
        max = numbers[i];
}

关于java - 从文本文件中查找最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33057600/

相关文章:

arrays - 矢量化- Matlab

java - 为什么 File.exists 返回误报

algorithm - 给定文件名列表,返回具有相同内容的文件列表列表 - 面试题

c - 使用 Execl 执行我的程序

java - 如何在 Java 中将 64 位宽度的二进制字符串转换为 long?

java - Zip 文件大小异常

java - java中比较两个数组并返回相等的个数

javascript - 是否可以操作 Array.prototype.map() 的索引参数?

java - 在 Controller Spring MVC中控制异常流

android - 关于安卓首选项