繁体   English   中英

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

[英]How can I read and compare numbers from a text file?

我有一个文本文件,eclipse可以毫无问题地读取它。 问题是我不知道如何保存FileReader中的数字。 我的程序应该从文件中读取文本,该文件有2个名称及其学习点。

例如:

杰克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");
    }
}

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

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");
    }
}

这可能不是解决问题的最有效方法,但我尝试了一下。 它不是用于比较多行的完整代码,但是您可以通过一个while循环运行它,直到文件不再像您已经做的那样为止。 一旦执行完此操作,就可以将每行的值存储到一个变量中,然后比较这些变量。 例如:布尔值xIsBigger x> y;。 然后,如果为true,则x是较大的数字,但如果为false,则您知道y是较大的数字。 希望这可以帮助。

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));

}

}

系统输出:60。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM