【发布时间】: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];whatsinteger -
可能有助于向我们展示来自
numbers.txt的一些内容。 -
也许你想删除这个问题。或者在最坏的情况下自己回答。就目前而言,这不是一个有用的问题。
-
它实际上只是一个包含 10,000 个数字的文本文件,每行一个数字。目前它列出文件中的第一个数字,而不是搜索整个文件。
-
在本地运行它,它似乎工作。这可能是 numbers.txt 文件的问题。这可能与行尾有关,并且 temp.isEmpty() 被触发并提前结束循环
标签: java arrays file search logic