2012-12-09 75 views
2

我有以下的文本文件:如何從文本文件存儲到數組行標記中?

First Name : Javier Last Name : Smith E-mail : [email protected] Password: jsmith Date of Birth: Jan 1, 1987 

First Name : Jade Last Name : Tux E-mail : [email protected] Password: jade123 Date of Birth: Jan 1, 1954 

First Name : Bruce Last Name : Porto E-mail : [email protected] Password: br11 Date of Birth: Feb 25, 1946 

我想在第一行中的字符串哈維爾,史密斯,史密斯@ .COM,JSMITH等等這些字符串存儲在類型的數組列表人(字符串,tring,字符串,字符串)並對每行執行相同的操作。

這是到目前爲止我的代碼:

try 
{ 
    searchUser = new Scanner(new FileInputStream("src/users.txt")).useDelimiter(":"); 
    String storeFirst = "", storeLast = "", storeEmail = "", storePassword = ""; 
    usersArray = new ArrayList<Person>(); 
    String line = null; 

    while(searchUser.hasNextLine()) 
    { 
     line = searchUser.nextLine(); 
      storeFirst = searchUser.next(); 
     storeLast = searchUser.next(); 
     storeEmail = searchUser.next(); 
     storePassword = searchUser.next(); 
     line = searchUser.nextLine(); 

     usersArray.add(new Person(storeFirst, storeLast, storeEmail, storePassword)); 

     for(Person ae : usersArray) 
     { 
      System.out.println(ae.toString()); 
     } 
     System.out.println(storeFirst); 
     System.out.println(storeLast); 
     System.out.println(storeEmail); 
     System.out.println(storePassword); 

    } 
    searchUser.close(); 
} 
+0

你可以提供一些關於你對當前代碼的確切問題以及你想要什麼的更多信息對嗎?目前看起來有點像「請完成我的任務」。 (如果這是一項任務,請在你的問題中說明這一點。) – Calrion

+0

這是我CS課的單獨項目...每個人都試圖想出一個不同的項目..所以我創建了這個項目。我想要做的是圖書館數據庫。所以程序會問你是否是圖書館的成員,如果你不是會員,你註冊並輸入信息,如果你是會員,你登錄。 – jv0006

+0

所以我想要做的是將所有的圖書館用戶轉換爲文本文件,當用戶嘗試登錄時,程序將搜索文本文件,並且如果用戶的電子郵件和密碼與文本文件上的電子郵件和密碼相匹配,則屏幕上會顯示一個代表「歡迎」的代碼。所以我想要做的就是將文本文件存儲到數組列表中,以便更容易地查找用戶電子郵件和密碼是否匹配! – jv0006

回答

1

更改while循環讀取和第一填充數組,然後有打印外循環爲:

while(searchUser.hasNextLine()){ 
    //read the tokens first ignoring tag tokens 
    searchUser.next();//ignore "First Name" 
    storeFirst = searchUser.next().split(" ")[0];//split the 3 words and take 1st 
    storeLast = searchUser.next().split(" ")[0];//split the 2 words and take 1st 
    storeEmail = searchUser.next().split(" ")[0];//split the 2 words and take 1st 
    storePassword = searchUser.next().split(" ")[0];//split the 2 words and take 1st 
    //read and ignore remaining text including the new line character in the end 
    searchUser.nextLine(); 

    Person person = new Person(storeFirst, storeLast, storeEmail, storePassword); 
    usersArray.add(person); 
} 

現在有打印代碼:

for(Person ae : usersArray){ 
    System.out.println(ae.toString()); 
} 
+0

謝謝@YogendraSingh!它的工作..現在,我的問題是,當掃描器到達文件的結尾時,它會輸出一個'NoSuchElementElementException'...我不知道我在這裏失去了什麼! – jv0006

+0

@ user1889004您可能在文件末尾有空行。上面的代碼假定如果有任何一行,它包含所有的標記。要解決該問題,請嘗試下列其中一項。 1.從文件末尾刪除空白行。 2.將上面代碼中的第一行更改爲'String firstNameTag = searchUser.next(); if(firstNameTag.isEmpty()){break;}'如果該行爲空則打破循環。如果它沒有解決您的問題,請告訴我。 –

+0

再次感謝@yogendra snigh ..經過了很長時間,弄清楚什麼是錯誤的,我發現所有的聯繫人都有空白。所以,它返回了這個異常錯誤!現在,它正在工作,因爲它應該:)!再次感謝1 – jv0006