簡體   English   中英

如何從命令行作為參數輸入的文本文件中讀取逗號分隔的字符串?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM