【问题标题】:Finding Max Value From Text File从文本文件中查找最大值
【发布时间】:2015-10-10 18:38:25
【问题描述】:

我一直在努力提高我的 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);
    }
}

【问题讨论】:

  • int max = integer[0];whats integer
  • 可能有助于向我们展示来自numbers.txt 的一些内容。
  • 也许你想删除这个问题。或者在最坏的情况下自己回答。就目前而言,这不是一个有用的问题。
  • 它实际上只是一个包含 10,000 个数字的文本文件,每行一个数字。目前它列出文件中的第一个数字,而不是搜索整个文件。
  • 在本地运行它,它似乎工作。这可能是 numbers.txt 文件的问题。这可能与行尾有关,并且 temp.isEmpty() 被触发并提前结束循环

标签: java arrays file search logic


【解决方案1】:

是的,有一个错误,但不是你的逻辑,以前缺少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];
}

【讨论】:

  • 在所有内容中添加大括号(大括号)是您应该养成的习惯。它会让你一次又一次地摆脱这种痛苦。我会踢任何不把它们放进去的后辈。因此,你也应该把它们添加到 if 中。
  • 完全同意@Xetius
  • 我添加了括号,但它似乎仍然没有找到最大的数字。仍然给出与以前相同的数字,列表中的第一个。
  • 我同意这应该是一种习惯,对于这种情况仍然无关紧要,因为for 循环后面跟着if 条件。检查here
  • 花括号将如何影响这种特殊情况???这里似乎没有什么超出范围
【解决方案2】:

问题出在您的 numbers.txt 文件中。将取决于您所在的平台以及预期的行尾,但我相信代码有效。

我在 Mac 上运行此代码,在 IntelliJ 中使用包含随机数的 txt 文件。它必须触发 temp.isEmpty() 条件并在读取第一项后退出。

检查文件,尤其是行尾。

另外,如果您无法在调试模式下单步执行代码,请尝试添加一些 System.out.println 语句以澄清发生了什么。

此代码对我有用。

【讨论】:

  • 会有什么不同?在我的文件中,每个数字都由行分隔,并且没有额外的空格。
  • 正如我上面提到的,尝试单步执行,看看你得到了什么值,或者使用 System.out 添加一些日志记录,你应该能够很容易地找到问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
相关资源
最近更新 更多