簡體   English   中英

用java讀取一個特殊的txt文件

[英]Reading a special txt file in java

我想要做的是讀取一個包含人和動物的文本文件。 它將編譯但在我嘗試運行時出錯。 我想我需要一個 for 循環來讀取 stringtokenizer 來解密 txt 文件中的人類和動物,到目前為止這是我的驅動程序類。

txt文件:

Morely,Robert,123 Anywhere Street,15396,4,234.56,2
Bubba,Bulldog,58,4-15-2010,6-14-2011
Lucy,Bulldog,49,4-15-2010,6-14-2011
Wilder,John,457 Somewhere Road,78214,3,124.53,1
Ralph,Cat,12,01-16-2011,04-21-2012
Miller,John,639 Green Glenn Drive,96258,5,0.00,3
Major,Lab,105,07-10-2012,06-13-2013
King,Collie,58,06-14-2012,10-05-2012 
Pippy,cat,10,04-25-2015,04-25-2015
Jones,Sam,34 Franklin Apt B,47196,1,32.09,1
Gunther,Swiss Mountain Dog,125,10-10-2013,10-10-2013
Smith,Jack,935 Garrison Blvd,67125,4,364.00,4
Perry,Parrot,5,NA,3-13-2014
Jake,German Shepherd,86,11-14-2013,11-14-2013 
Sweetie,tabby cat,15,12-15-2013,2-15-2015
Pete,boa,8,NA,3-15-2015 

來源:

import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.File;
import java.io.IOException;
/**
 * This is my driver class that reads from a txt file to put into an array and uses the class refrences so it can use the menu and spit out  
 * 
 * @author ******
 * @version 11/25/2015
 */
public class Driver
{
    /**
     * Constructor for objects of class Driver, what it does is read in the txt file gets the two class refrences and loops through to read through the whole file looking for string tokens to go to the next line
     * and closes the file at the end also uses for loop to count number of string tokens to decipher between human and pets.
     */
    public static void main(String[] args) throws IOException
    {
        Pet p;
        Human h;
        Scanner input;
        char menu;
        input = new Scanner(new File("clientdata.txt"));

        int nBalance;
        int id;

        /**
         * this while statement goes through each line looking for the string tokenizer ",". I want to count each "," to decipher between Human and Animal
         */
        while(input.hasNext())
        {
            StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
            h = new Human();
            h.setLastName(st.nextToken());
            h.setFirstName(st.nextToken());
            h.setAddress(st.nextToken());
            h.setCiD(Integer.parseInt(st.nextToken()));
            h.setVisits(Integer.parseInt(st.nextToken()));
            h.setBalance(Double.parseDouble(st.nextToken()));
            p = new Pet(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(), st.nextToken());
        }
        /**
         * this is my seond while statement that loops the case switch statements and asks the user for client ID
         */
        menu = 'Y';
        while(menu == 'y' || menu == 'Y') {
            System.out.print("\nChose one:\n A- client names and outstanding balance \n B- client's pets, name, type and date of last visit\n C-change the client's outstanding balance: ");
            menu = input.next().charAt(0);
            System.out.print("Enter client ID: ");
            id = input.nextInt();
            h = new Human();
            if(id == h.getCiD())//if the id entered up top is equal to one of the id's in the txt file then it continues to the menu
            {
                p = new Pet();
             switch(menu)
       {    case 'A':
            System.out.println("client name: " + h.getFirstName() + "outstanding balance: " + h.getBalance());
             break;
             case 'B':
             System.out.println("pet's name: " + p.getName() + "type of pet: " + p.getTanimal() + "date of last visit: " + p.getLastVisit());
             break;
             case 'C':
             System.out.println("what do you want to change the clients balances to?");


        input.close();
       }
    }
    else// if not then it goes to this If statement saying that the Client does not exist
    { 
        System.out.println("Client does not exist.");
    }
   }
}
}

您有許多問題需要克服...

  • 對於每一行,您需要確定該行代表的數據類型
  • 您需要某種方式來跟蹤您加載的數據(客戶及其寵物)
  • 您需要某種方式將每只寵物與其主人聯系起來

第一個可以通過多種方式完成,假設我們可以更改數據。 您可以使第一個標記有意義( humanpet ); 您可以改用 JSON 或 XML。 但讓我們暫時假設,您無法更改格式。

這兩種數據的主要區別在於它們包含的令牌數量,人為 7,寵物為 5。

while (input.hasNext()) {
    String text = input.nextLine();
    String[] parts = text.split(",");
    if (parts.length == 7) {
        // Parse owner
    } else if (parts.length == 5) {
        // Parse pet
    } // else invalid data

對於第二個問題,您可以使用數組,但您需要提前知道您需要的元素數量、人數以及每個人的寵物數量

奇怪的是,我剛剛注意到最后一個元素是一個int並且似乎代表了寵物的數量!!

Morely,Robert,123 Anywhere Street,15396,4,234.56,2
                                     ------------^

但這對我們的業主沒有幫助。

對於所有者,您可以使用某種List ,每當您創建一個新的Human ,您只需將它們添加到List ,例如...

List<Human> humans = new ArrayList<>(25);
//...
    if (parts.length == 7) {
        // Parse the properties
        human = new Human(...);
        humans.add(human);
    } else if (parts.length == 5) {

第三,對於寵物,每個Pet都應該與主人直接相關,例如:

Human human = null;
while (input.hasNext()) {
    String text = input.nextLine();
    String[] parts = text.split(",");
    if (parts.length == 7) {
        //...
    } else if (parts.length == 5) {
        if (human != null) {
            // Parse pet properties
            Pet pet = new Pet(name, type, age, date1, date2);
            human.add(pet);
        } else {
            throw new NullPointerException("Found pet without human");
        }
    }

好的,所有這些都是每次我們創建一個Human ,我們都會保留對創建的“當前”或“最后一個”所有者的引用。 對於我們解析的每個“寵物”行,我們將其添加到所有者。

現在, Human類可以使用數組或List來管理寵物,兩者都可以,因為我們知道寵物的預期數量。 然后,您將在Human類中提供 getter 以獲取對 pet 的引用。

因為上下文之外的代碼可能難以閱讀,這是您可能能夠執行的操作的示例...

Scanner input = new Scanner(new File("data.txt"));
List<Human> humans = new ArrayList<>(25);
Human human = null;
while (input.hasNext()) {
    String text = input.nextLine();
    String[] parts = text.split(",");
    if (parts.length == 7) {
        String firstName = parts[0];
        String lastName = parts[1];
        String address = parts[2];
        int cid = Integer.parseInt(parts[3]);
        int vists = Integer.parseInt(parts[4]);
        double balance = Double.parseDouble(parts[5]);
        int other = Integer.parseInt(parts[6]);
        human = new Human(firstName, lastName, address, cid, vists, balance, other);
        humans.add(human);
    } else if (parts.length == 5) {
        if (human != null) {
            String name = parts[0];
            String type = parts[1];
            int age = Integer.parseInt(parts[2]);
            String date1 = parts[3];
            String date2 = parts[4];
            Pet pet = new Pet(name, type, age, date1, date2);
            human.add(pet);
        } else {
            throw new NullPointerException("Found pet without human");
        }
    }
}

使用split()函數而不是使用StringTokenizer怎么樣?

說,你可以改變你的第一個while循環,如下所示:

while (input.hasNext()) {
//  StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
    String[] tokens = input.nextLine().split(",");
    if (tokens.length == 7) {
        h = new Human();
        h.setLastName(tokens[0]);
        h.setFirstName(tokens[1]);
        h.setAddress(tokens[2]);
        h.setCiD(Integer.parseInt(tokens[3]));
        h.setVisits(Integer.parseInt(tokens[4]));
        h.setBalance(Double.parseDouble(tokens[5]));
    } else {
        p = new Pet(tokens[0], tokens[1], Integer.parseInt(tokens[2]), tokens[3], tokens[4]);
    }
}

而對於跟蹤哪些寵物屬於哪個人的,可以追加型的ArrayList PetHuman的類象下面這樣:

ArrayList<Pet> pets = new ArrayList<>();

說你有另一個ArrayList類型的Human命名為humans的主要功能。 因此,您可以添加if塊,例如:

humans.add(h);

else部分,您可以附加到else塊中:

humans.get(humans.size()-1).pets.add(p);

您可以嘗試這樣的操作 - 填充地圖,然后使用它您可以根據您的要求分配值。

public void differentiate(){
    try {
        Scanner scan=new Scanner(new BufferedReader(new FileReader("//your filepath")));
            Map<String,List<String>> map=new HashMap<String, List<String>>();
            while(scan.hasNextLine()){
            List<String> petList=new ArrayList<String>();
            String s=scan.nextLine();
            String str[]=s.split(",");
            String name=str[1]+" "+str[0];
            int petCount=Integer.parseInt(str[str.length-1]);
                for(int i=1;i<=petCount;i++){
                 String petString=scan.nextLine();
                 petList.add(petString);
                }
                map.put(name, petList);
            }
            Set<String> set=map.keySet();
            for(String str:set){
                System.out.println(str+" has "+map.get(str)+" pets");
            }
        } 
        catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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