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