如何读取和比较文本文件中的数字?

时间:2016-04-11 23:47:40

标签: java

我是一个文本文件,eclipse读取没有问题。问题是我不知道如何从FileReader中保存数字。我的程序应该从一个文件中读取一个文件,该文件有2个名字和他们的学校点。

例如:

  

Jack 30 30 30
  马丁20 20 30

如何找到分数更高的那个?

public static void main(String[] args)  {
    String name = null;
    try {
        Scanner keybord = new Scanner(System.in);
        System.out.println("enter in file name");
        String filename = keybord.nextLine();
        Scanner file = new Scanner(new File(filename));

        while (file.hasNext())
        {
            name = file.nextLine();
            System.out.println(name);

            ///?? what do i have to write to compare to persons points
        }
    } catch(IOException e) {
        System.out.println("The file does not exist");
    }
}

2 个答案:

答案 0 :(得分:1)

我知道,这不是一种有效的方法,但我用这段代码解决了这个问题:

public static void main(String[] args)
{
    String name = null;
    int i = 0;
    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;
    try
    {
        Scanner keybord = new Scanner(System.in);
        System.out.println("enter in file name");
        String filename = keybord.nextLine();
        Scanner file = new Scanner(new File(filename));

        while (file.hasNext())
        {
            name = file.next();
            System.out.println(name + " ");

            while (file.hasNextInt())
            {
                i = i + file.nextInt();
            }
            if (i < min)
            {
                min = i;
            }
            System.out.println("min " + min);
            if (i > max)
            {
                max = i;
            }
            System.out.println("max " + max);
            i = 0;
        }
    } catch (IOException e)
    {
        System.out.println("File does not exist");
    }
}

答案 1 :(得分:0)

This probably isn't the most efficient way of solving it, but I gave it a shot. It isn't the full code for comparing multiple lines but you can just run this through a while loop until the file doesn't have next like you were already doing. Once you run this through you can store the value of each line to a variable and then compare the variables. ex: boolean xIsBigger x > y;. Then if it is true, x is the bigger number but if it is false then you know y is the bigger number. Hope this helps.

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

public class Test {

    public static void main(String[] args) throws ScriptException {
        String line = "Jack 20 20 20";

        line = line.replaceAll("[^0-9]", " ");

        line = line.replaceFirst("^ *", "");

        line = line.replaceAll(" ", "+");

        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");

        System.out.println(engine.eval(line));

}

}

System output: 60.