![](/img/trans.png)
[英]How do I print lines from a command-line input file to a command-line output file?
[英]How do I read in comma separated string from text file that is inputted from command-line as argument?
我正在编写一个对医院记录进行排序的程序。 这些记录位于一个文本文件中,当用户调用下面的“患者”类时,用户会在命令行中将其作为参数输入。 文本文件中每一行的记录格式为姓(字符串),名字(字符串),房间号(int),年龄(int)。 行数未知。 用户将文件名指定为第一个参数,然后指定要排序的字段。 我要特别弄清楚的是如何读取文本文件并将信息存储在数组中。 到目前为止,我已经坚持了大约一个星期,所以我从头开始了几次。 这是我到目前为止所拥有的。
import java.util.*;
import java.io.*;
public class Patient
{
public static void main(String args[])
{
System.out.println("Servando Hernandez");
System.out.println("Patient sorting Program.");
Scanner scan = new Scanner(args[0]);
String[] Rec = new String[10];
while(scan.hasNextLine)
{
scan.nextLine = Rec[i];
}
Arrays.sort(Rec);
for(int j=0; j<Rec.length; j++)
{
System.out.println(Rec[j]);
}
}
}
行数未知
这表明您需要一个可以增长以满足您需求的动态数据结构。 考虑使用某种List
List<String> lines = new ArrayList<>(10);
while(scan.hasNextLine)
{
lines.add(scan.nextLine());
}
查看Collections Trail了解更多详细信息
因为您正在处理结构化数据,所以我会考虑创建某种POJO以使其更易于管理...
public class PatientRecord {
private final String firstName;
private final String lastName;
private final int roomNumber;
private final int age;
public PatientRecord(String firstName, String lastName, int roomNumber, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.roomNumber = roomNumber;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getRoomNumber() {
return roomNumber;
}
public int getAge() {
return age;
}
}
然后,当您从文件中读取该行时,您将对其进行解析,创建一个新的PatientRecord
实例,并将其添加到您的List
。
这意味着您可以根据需要使用Collections.sort
类的东西对List
进行排序
现在,我不太确定这正是您想要的,因为您给我的代码并不多,但这是您的相同代码,已固定,稍作重构,并设置为在读取行时返回这些行,但按姓氏排序:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Patient {
public static void main(String args[]) {
System.out.println("Servando Hernandez");
System.out.println("Patient sorting Program.");
Scanner scan = null;
try {
scan = new Scanner(new File(args[0]));
} catch (FileNotFoundException e) {
System.err.println("File path \"" + args[0] + "\" not found.");
System.exit(0);
}
ArrayList<String> lines=new ArrayList<String>();
while(scan.hasNextLine())
lines.add(scan.nextLine());
Collections.sort(lines);
for(String x : lines)
System.out.println(x);
}
}
希望对您有所帮助,并祝您好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.