gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:36:14 25 4
gpt4 key购买 nike

我有一个如下所示的文本文件

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

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

java Codes

Enter file name >> stationsMaster.txt

Enter station code >> FSS

Station name: "Flinders" has code "FSS" date built: 12 September 1854

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

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

}

最佳答案

您可以尝试这样的操作:希望这可以解决您的问题

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

}

关于Java从用户输入中读取txt文件并根据用户输入输出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38892471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com