我已经接受了这个问题的实践,并且有点坚持如何完成它。它基本上要求我们创建一个程序,该程序使用BufferedReader对象读取txt文件中给出的值(55,96,88,32)(比如“s.txt”),然后返回给定值的最小值。 到目前为止,我有两个部分的程序,但我不知道如何将它们连接在一起。
import java.io.*;
class CalculateMin
{
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
int numberOfLines = 5;
String[] textInfo = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
textInfo[i] = br.readLine();
}
br.close();
} catch (IOException ie) {
}
}
}
然后我有我做的循环,但我不知道如何将其实现到上面的程序中。我知道我让事情复杂化了。
int[] numArray;
numArray = new int[Integer.parseInt(br.readLine())];
int smallestSoFar = numArray[0];
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] < smallestSoFar) {
smallestSoFar = numArray[i];
}
}
感谢您的帮助
答案 0 :(得分:0)
尝试此代码,它会遍历整个文件,将每行的数字与先前读取的最低数字进行比较 -
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
String line;
int lowestNumber = Integer.MAX_VALUE;
int number;
while ((line = br.readLine()) != null) {
try {
number = Integer.parseInt(line);
lowestNumber = number < lowestNumber ? number : lowestNumber;
} catch (NumberFormatException ex) {
// print the error saying that the line does not contain a number
}
}
br.close();
System.out.println("Lowest number is " + lowestNumber);
} catch (IOException ie) {
// print the exception
}
}