簡體   English   中英

讀取文件的最大和最小數量

[英]Readfile max and min number

我確實需要解決我正在解決的問題。 我正在嘗試在.txt文件中找到最大和最小數字,該數字可以是它只需要讀取文件然后打印出最大和最小數字的任何數字。 讀取文件工作正常,唯一的問題是我只得到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);                   
   }
}

不明白我在做什么錯,任何提示或幫助將不勝感激!

您正在從文件中獲取編號,但此后您將不再使用它。

     int number = inputFile.nextInt();

     if ( number > max)
     {
         max = number ;
     }
     if ( number < min)
     {
         min = number ;
     }

或代替將val更改為number,而更改行:

int number = inputFile.nextInt();

val = inputFile.nextInt();
val = inputFile.nextInt();

代替

int number = inputFile.nextInt();

因為您讀取了每一行並將其分配給名為number的新變量。 但是您正在檢查val變量。 因此,結果為0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM