在java中读取一个特殊的txt文件

时间:2015-11-26 04:38:09

标签: java arrays

我想要做的是阅读包含人类和动物的文本文件。它会编译但在我尝试运行它时会出错。我想我需要一个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.");
    }
   }
}
}

3 个答案:

答案 0 :(得分:2)

您需要克服许多问题......

  • 对于每一行,您需要确定该行代表的数据类型
  • 您需要一些方法来跟踪您(客户及其宠物)的数据
  • 您需要某种方式将每只宠物与其主人
  • 相关联

假设我们可以更改数据,第一种方法可以通过多种方式完成。您可以使第一个令牌有意义(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时,我们都会引用&#34;当前&#34;或者&#34;最后&#34;所有者创建。对于每个宠物&#34;我们解析的行,我们将其添加到所有者。

现在,Human类可以使用数组或List来管理宠物,或者可以使用,因为我们知道预期的宠物数量。然后,您将在Human课程中提供获取者以获取对宠物的参考。

因为上下文代码很难阅读,所以这是你可以做的一个例子......

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

答案 1 :(得分:0)

如何使用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]);
    }
}

为了跟踪哪个宠物属于哪个人类,您可以在Pet类中添加类型为Human的arrayList,如下所示:

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

并说主要功能中有另一个ArrayList类型为Human humans的{​​{1}}。因此,您可以在if块中追加:

humans.add(h);

并在else部分,您可以在else块中附加:

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

答案 2 :(得分:0)

你可以尝试这样的事情 - 填充地图然后使用它可以根据您的要求分配值。

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

}