将数据拆分为数组

时间:2017-12-01 09:35:25

标签: java arrays csv

public class ImportDoctorFile  {

    public ImportDoctorFile() {
              System.out.println("Starting Cons");

     List<Doctor> doctorList = new ArrayList<>();
            Scanner scanner;
      try
        {
             scanner= new Scanner(new File("Doctors.csv"));
              scanner.useDelimiter("\n");
             while (scanner.hasNextLine())
            {        
                String temp = scanner.nextLine();
                String [] tempDetails = temp.split(",");

                Doctor myDoctor;
                Surgeon mySurgeon;

                if(tempDetails.length == 5)
                {                   
                    myDoctor =new Doctor (tempDetails[0],tempDetails[1],tempDetails[2],tempDetails[3],tempDetails[4]);
                    doctorList.add(myDoctor);
                    System.out.println(myDoctor);                    
                }                
                else if(tempDetails.length ==6)
                {
                    mySurgeon =new Surgeon (tempDetails[0],tempDetails[1],tempDetails[2],tempDetails[3],tempDetails[4],tempDetails[5]);
                    doctorList.add(mySurgeon);
                    System.out.println(mySurgeon);
                }      
            }
        }
      catch(FileNotFoundException e) 
        {
            System.out.print("Error, unable to locate the CSV File!");

        }                        
    }     
}

尝试将我的.csv文件中的数据加载到数组中并将其拆分时出现问题。在输出细节时,它会跳过一些医生,并在创建外科医生时错过第6个索引。我已粘贴上面的csv文件。

Conor Murphy 12 Front Road Leeds电话conor@hotmail.com手术12/05/2016

Carol McKee 79 The Green Birmingham Skype Cmckee-25 Neurology

Robert Jones 165 Main Street格拉斯哥Facetime R.jones@gmail.com骨科

Mary Shelley 297 Peartree Grove Guildford Skype m-shelly1 Cardiology

John Smith 13 Value Avenue Bristol电话:+44(0)7987545352手术12/05/2016

Laura Penny 87 Primrose Way Ipswich Facetime l.penny234@btinternet.com Pulmonology

Mark Matthews 2 The Strand Dublin Skype Matthews-m15 Int.Care Medicine

Ciaran Bell 58 Windy Ridge Folkstone电话+44(0)8452126984传染病

Nicola Johnson 128 Ash Park Coleraine Skype Nicky-j123手术24/11/2015

1 个答案:

答案 0 :(得分:0)

您可以使用StringBuilder

StringBuilder类具有将其内容转换为标记的属性。 只需添加','作为分隔符,您就可以获得令牌。