Java从用户输入读取txt文件并根据用户输入输出数据

时间:2016-08-11 09:31:21

标签: java

我有一个看起来像这样的文本文件

BEG#Belgrave#19 February 1962
FSS#Flinders Street#12 September 1854
TSN#Tecoma#1 February 1924

我试图编写程序,要求用户输入文件名(我可以做这部分),然后提示用户输入“代码”。然后程序读取txt文件,并根据唯一代码输出信息。 例如:

  

java代码

     

输入文件名>> stationsMaster.txt

     

输入电台代码>> FSS

     

电台名称:“Flinders”的代码为“FSS”日期:1854年9月12日

这是我到目前为止所做的代码,我只是真的坚持如何编写代码,以便程序读取文本文件并从用户输入输出相关信息。

import java.util.*;
import java.io.*;
public class Codes
{
public static void main (String [] args) throws IOException
{
 Scanner keyboard = new Scanner (System.in);
 System.out.print("Enter File Name");
 String filename = keyboard.nextLine();
 File f = new File (filename);
 Scanner fin = new Scanner (f);
 String stationcode = fin.nextLine();
 String stationname = fin.nextLine();
 String date = fin.nextLine ();


while (fin.hasNextLine ( ) )
 {

System.out.print (date);
System.out.print(stationname);

 }

fin.close ();

}

1 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情:希望这可以解决你的问题

public class Test {
    private Map<String, Station> stationMap = new HashMap<>();

    public static void main(String[] args) throws Exception {
        // first read the file and store the data to the map
        Test test = new Test();
        test.readFile();

        // now ask the user for the station code
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("Please enter the code: ");
            String code = scanner.nextLine();
            Station station = test.stationMap.get(code.toUpperCase());
            if (station == null) {
                System.out.println("There is no such station present fot this code!");
                continue;
            }
            System.out.println("Station name: "+station.getName());
            System.out.println("Station code: "+station.getCode());
            System.out.println("Station built date: "+station.getBuiltDate());
        }
    }

    private void readFile() {
        try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("path/to/file")))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strs = line.split("#");
                Station station = new Station(strs[0], strs[1], strs[2]);
                stationMap.put(station.getCode().toUpperCase(), station);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class Station {
        private String name;
        private String code;
        private String builtDate;

        public Station(String name, String code, String builtDate) {
            this.name = name;
            this.code = code;
            this.builtDate = builtDate;
        }

        public String getName() {
            return name;
        }

        public String getCode() {
            return code;
        }

        public String getBuiltDate() {
            return builtDate;
        }
    }

}