【问题标题】:Readfile max and min number读取文件最大和最小数量
【发布时间】:2014-12-09 23:23:47
【问题描述】:

我确实需要帮助解决我正在处理的问题。我试图在 .txt 文件中找到最大和最小数字,它可以是任何数字,它只需要读取文件然后打印出最大和最小数字。 readfile 工作正常,唯一的问题是我只能得到 0 的答案。

我的代码:

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

public class LargeSmall
{
   public static void main(String[] args) throws IOException
   {
      //gets filename
      Scanner keyboard = new Scanner(System.in);
      System.out.println("Enter the name of the file: ");
      String filename = keyboard.nextLine();

      //opens file
      File file = new File(filename);
      Scanner inputFile = new Scanner(file);

      //place holders for varibales
      int val = 0;
      int max = Integer.MIN_VALUE;
      int min = Integer.MAX_VALUE;

      //to read all lines of file
      while (inputFile.hasNext())
      {
         //gets min and max number
         int number = inputFile.nextInt();

         if ( val > max)
         {
         max = val;
         }

         if ( val < min)
         {
         min = val;
         }
      }
   //Close file
   inputFile.close();

   //Print out lowest value in the list and highest
   System.out.println("Min number is: " +min);
   System.out.println("Max number is: " +max);                   
   }
}

不明白我做错了什么,任何提示或帮助将不胜感激!

【问题讨论】:

    标签: java max min readfile


    【解决方案1】:
    val = inputFile.nextInt();
    

    而不是

    int number = inputFile.nextInt();
    

    因为您读取了每一行并将其分配给名为 number 的新变量。但是您正在检查 val 变量。所以它给出的结果是 0。

    【讨论】:

      【解决方案2】:

      您正在从文件中获取号码,但之后您再也不会使用它。

           int number = inputFile.nextInt();
      
           if ( number > max)
           {
               max = number ;
           }
           if ( number < min)
           {
               min = number ;
           }
      

      或者不是将 val 更改为数字,而是更改行:

      int number = inputFile.nextInt();
      

      到

      val = inputFile.nextInt();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-01
        • 2015-12-13
        • 1970-01-01
        • 2010-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多