从Java中的文件中读取整数

时间:2017-04-07 17:36:09

标签: java

我正在尝试用Java中的文件读取整数并显示最高值,但我很难想到它。

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

public class MyFile
{
    public static void main(String[] args) throws Exception
    {
        String filename;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter the name of the file.");

        filename = in.nextLine();
        File file = new File("myFile.txt");
        Scanner inputfile = new Scanner(file);
        while(inputfile.hasNext())
        {
            int compare = inputfile.nextInt();
        }
    }
}

该文件名为myFile.txt,整数为23,34,45和2.

3 个答案:

答案 0 :(得分:3)

如果您需要从文件中找到最高值,您可以执行以下操作:

int max = Integer.MIN_VALUE;
while(inputfile.hasNext()) {
     int compare = inputfile.nextInt();
     if (compare > max){
         max = compare;
     }
}
System.out.println("highest value:"+ max);

这是你在找什么?

答案 1 :(得分:0)

声明变量maxValue。使用文件中的文件值初始化此值。循环文件的其余部分,将新读取的值与maxValue进行比较。如果新读取的值大于maxValue。将maxValue分配给该值。

答案 2 :(得分:0)

Javadoc声明:

  

扫描仪使用分隔符模式将其输入分解为标记,   默认情况下匹配空格。您的文件应包含

23 34 45 2

之间没有逗号