如何在java的文本文件中搜索和匹配? [英] How do I search and match in text file for java?

查看:626
本文介绍了如何在java的文本文件中搜索和匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写一个代码,允许用户输入邮政编码和程序返回该邮政编码的城市。



文本文件示例(非常大的文本文件)



EHFD324华盛顿

SAFRE纽约

EH54 Livingston

等.....



我是得到错误,程序只询问输入邮政编码。一旦我输入邮政编码,我就会收到错误。



我尝试了什么:



I try to write a code which allow users to type the postcode and program return city for that postcode.

Example of text file (it is very large text file)

EHFD324 Washington
SAFRE New York
EH54 Livingston
and etc .....

I am getting error, the program only asked for "Enter the postcode". Once I entering the postcode I am getting error.

What I have tried:

  public static void main(String[] args) throws FileNotFoundException
    {
        try
        {
            File f = new File("Files\\cities.txt");
            Scanner input = new Scanner(f);
            String text;
            while(input.hasNextLine())
            {
                text = input.nextLine();
                process(text);
            }


        }
        catch (FileNotFoundException ex)
        {
            System.out.println(ex.getMessage());
        }   
    }

    public static void process(String text)
    {   String name = null;
    int id;
        Scanner code = new Scanner(System.in);
        System.out.println("enter the postcode");       
        id = code.nextInt();
        Scanner data = new Scanner(text);

         if(code.equals(0))System.out.println(name);

        name = data.next();
        id = data.nextInt();

        while(data.hasNextDouble())
        {

        }
    System.out.println(name+ " ");

    }
}

推荐答案

你的程序被写回到前面。您需要做的第一件事是从用户那里获取邮政编码。并且不要尝试将其读作 int ,因为文件中的代码都是字符串。获得该字段后,您只需阅读将每个邮政编码与输入的邮政编码进行比较的文件。最后,为什么你在文本中没有双重值时使用 nextDouble



查看你的来源文件格式并仔细考虑如何搜索它以匹配数据。
Your program is written back to front. The first thing you need to do is to get the postcode from the user. And do not try to read it as an int since the codes in your file are all character strings. Once you have that field you just read the file comparing each postcode to the one entered. And lastly why are you using nextDouble when there are no double values in the text?

Look at your source file format and think carefully how you need to search through it to match the data.


这篇关于如何在java的文本文件中搜索和匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆