gpt4 book ai didi

java - 如何以特定格式显示txt文件中的数据

转载 作者:行者123 更新时间:2023-12-01 19:26:16 26 4
gpt4 key购买 nike

我有一个文本文件输入,其中包含如下数据。如何将文本文件中的数据显示为特定格式?

Monday
Jessy
Walking
20 minutes
Matthew
Run
20 minutes
Karen
Jogging
40 minutes
Jessica
Run
12 minutes
Tuesday
Messia
Walking
10 minutes
Matthew
Run
20 minutes
Pete
Run
10 minutes
Carol
Walking
30 minutes

我想将文本文件中的数据显示为以下格式:

Day            Name               Type of exercise           Time
Monday Jessy Walking 20 minutes
Matthew Run 20 minutes
Karen Jogging 40 minutes
Jessica Run 12 minutes
Tuesday Messia Walking 10 minutes
Matthew Run 20 minutes
Pete Run 10 minutes
Carol Walking 30 minutes

最佳答案

我只是快速地将它们组合在一起,但是像这样的东西怎么样:

static final String[] DAYS =
{ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

public class ActivityEvent
{
public int day;
public String name;
public String typeOfExercise;
public String time;
}

public List loadActivities(String filename) throws IOException
{
List activities = new ArrayList();
FileInputStream fis = new FileInputStream(filename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
int lastDay = -1;
String line;
while ((line = br.readLine()) != null)
{
line = line.trim();
int day;
for (day = DAYS.length - 1; day >= 0; day--)
{
if (line.equals(DAYS[day]))
{
break;
}
}
String name;
if (day < 0)
{
day = lastDay;
if (lastDay < 0)
{
throw new IOException(filename + " must start with day of week");
}
name = line;
}
else
{
name = br.readLine();
if (name == null)
{
throw new IOException(filename + " expected name, reached end of file");
}
}
String type = br.readLine();
if (type == null)
{
throw new IOException(filename + " expected type of exercise, reached end of file");
}
String time = br.readLine();
if (time != null)
{
throw new IOException(filename + " expected time of exercise, reached end of file");
}
ActivityEvent activity = new ActivityEvent();
activity.day = day;
activity.name = name;
activity.typeOfExercise = type;
activity.time = time;
activities.add(activity);
}
return activities;
}

public void printActivities(List activities)
{
StringBuilder str = new StringBuilder("Day\tName\tType of Exercise\tTime\n");
int numActivities = activities.size();
int lastDay = -1;
for (int index = 0; index < numActivities; index++)
{
ActivityEvent activity = (ActivityEvent)activities.get(index);
if (activity.day != lastDay)
{
str.append(DAYS[activity.day]);
}
str.append('\t');
str.append(activity.name);
str.append('\t');
str.append(activity.typeOfExercise);
str.append('\t');
str.append(activity.time);
str.append('\n');
}
System.out.print(str.toString());
}

然后调用所有内容,例如:

List activities = loadActivities("somefile.txt");
// Do optional sorting, etc. here.
printActivities(activities);

关于java - 如何以特定格式显示txt文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/731917/

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