使我的变量可以接受我的print语句

时间:2013-03-04 22:53:09

标签: java jgrasp

我在我的计划结束时遇到了麻烦。我知道,我的程序输入一个数字文件,并找到最低值。我的想法是如何写出我的最高值变量,以便它将通过我的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+ ".");
}

}

2 个答案:

答案 0 :(得分:2)

同意@rgettman。另外发生的事情是您的扫描仪正在读取整个文件但无法启动或反转。如果您要再次浏览文件,则需要创建一个新的扫描仪。

答案 1 :(得分: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;
}