2014-07-16 20 views
0

我有了的東西一樣, 湯姆,凱莉,珍文本文件使用分隔符開關掃描儀:0,馬特:2,喬恩如何在如果根據其分隔符被擊中

所以在這放置// if(******)我想使用list.add,那裏是Tom,Kelly,Jon,我希望在文件中使用位於0的文件中的掃描int作爲Jane,Matt。我不確定定界符是否是正確的選擇,我知道那裏的兩臺掃描儀都不正確。請指向正確的方向。

public static Picker fromFile() throws FileNotFoundException 
{ 
    ArrayList<Student> list = new ArrayList<Student>(); 
    Scanner diskScanner = new Scanner(new File("Names.txt")); 
    diskScanner.useDelimiter(", |:"); 

    while (diskScanner.hasNext()) { 

     //if(******) 
     list.add(new Student(0, diskScanner.next()));// or list.add(new Student(diskScanner.next(), diskScanner.next())) 
    } 
    list = Order.arrange(list); 

    Picker pick = new Picker(list); 
    return pick;  

回答

0

只要做到這一點,像這樣:

Scanner diskScanner = new Scanner(new File("Names.txt")); 
diskScanner.useDelimiter(","); 

while (diskScanner.hasNext()) 
    { 
    String n = diskScanner.next(); 

    if(n.contains(":")) 
     { 
     int i = n.indexOf(":"); 
     list.add(new Student(Integer.parseInt(n.substring(i+1)), n.substring(0,i))); 
     } 
    else 
     list.add(new Student(0, n)); 
    } 

未經檢驗的,所以請謹慎使用。你可以通過尋求一個過於優雅的解決方案來經常跳槽。只需獲取逗號之間的所有字符串,然後進行任何額外的解析。

+0

這真的看起來像它會起作用,但它不喜歡(int)n.substring(i + 1)。它會拋出不兼容類型的錯誤:java.lang.Srring不能轉換爲int。回到繪圖板。 – Chad

+0

我在這裏找到了解決方案https://stackoverflow.com/questions/5585779/how-to-convert-string-to-int-in-java它是int foo = Integer.parseInt(「1234」); – Chad

+0

@Chad對不起,那是因爲我用Java編寫了一段時間。我編輯了我的答案。如果您覺得現在滿意,如果您將其標記爲已接受,我將不勝感激。 – Azar

相關問題