0

我在我的程序结束时遇到了障碍。我知道我的程序一定会输入一个数字文件并找到最小值。我的障碍是如何写出我的最高值变量,以便它将通过我的 while 循环运行并为我的打印行语句分配一个值.....这是我的程序

import java.io.*;
import java.util.Scanner;


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

    //Open the file
    File file = new File("Numbers.txt");
    Scanner inputFile = new Scanner(file);


    String filename;                                 
    double lowest = inputFile.nextDouble();  //lowest first number in list
    double highest = lowest;

    //Read all the values in Numbers file 
    while (inputFile.hasNext())
    {
        //Read second value from file
        double number = inputFile.nextDouble();

        //Read the numbers in the file and compare each value to find lowest value
        if (number < lowest) 
            //The lowest number in the list has now been stored as lowest
            lowest = number;
    }

    //Reread all the values in Numbers file 
    while (inputFile.hasNext())
    {
        //number equals the second value in your list
        double number = inputFile.nextDouble();

        if (number > highest)   
            highest = number;
    }

    //Close file
    inputFile.close();

    //Print out the lowest value in the list
    System.out.println("The lowest number in your file called, " +
      "Numbers.txt is "   +lowest+ ".");

    System.out.println("The highest number in your file is, " +highest+ ".");
}

}

4

2 回答 2

2

同意@rgettman。此外,您的扫描仪正在读取整个文件,但无法重新开始或反转。如果您要再次浏览文件,则需要创建一个新的扫描仪。

于 2013-03-04T23:03:58.860 回答
1

没有理由有第二个while循环。在你的两个循环中,你用完了第一个循环中的所有值,而第二个循环中没有任何值。

您可以number在一个循环中执行最低和最高测试:

while (inputFile.hasNext())
{
   // Read second value from file
   double number = inputFile.nextDouble();

   // Read the numbers in the file and compare each value to find lowest value
   if (number < lowest) 
      //The lowest number in the list has now been stored as lowest
      lowest = number;

   // Find the highest value.
   if (number > highest)
      highest = number;
}
于 2013-03-04T22:57:59.990 回答