2017-04-01 36 views
1

我有以下格式,其中左邊一列是lineNumber右列一個簡單的.txt文件(「theFile.txt」)是word如何僅從.txt文件中選擇性地讀取數字和/或單詞?

5  today 
2  It's 
1  " 
4  sunny 
3  a 
6  " 

對於這個txt文件,我「M使得兩種不同的方法來每個得到數量和字符串,加上掃描文件,並把每個lineNumberword在雙鏈表另一種方法:

String fileName = "theFile.txt"; 

    public int getNumberOnly() { 
     int lineNumber; 

     //code to only get the lineNumber but NOT the words 
     //This is as far as I got and I need help on this part 

     return lineNumber; 
    } 

    public String getWordsOnly() { 
     String words; 

     //code to only get the words but NOT the lineNumber 
     //This is as far as I got and I need help on this part 

     return words; 
    } 

    public void readAndPrintWholeFile(String fileName){ 

      String fileContents = new String(); 
      File file = new File("theFile.txt"); 
      Scanner scanner = new Scanner(new FileInputStream(fileName)); 
      DLL<T> list = new DLL<T>(); 

     //Print each lineNumber and corresponding words for example 
     // 5 Today 
     // 2 It's 

     while (scanner.hasNextLine()) 
     { 
       fileContents = scanner.nextLine(); 
       System.out.println(list.getNumbersOnly() + " " + list.getWordOnly()); 
       //prints the lineNumber then space then the word 
     } 
    } 

    //I already have all DLL accessors and mutators such as get & set next/previous nodes here, etc. 

我卡在如何爲這兩種getNumbersOnly()getWordOnly()

我已經盡我所能去這個點的編碼方法體。謝謝你的幫助。

+0

把這個分爲兩種方法有什麼意義?這是作業嗎? –

+0

這是一個練習 - 我在這裏問,因爲我已經用盡了所有我知道的。 – 5120bee

+0

是通過空間均勻的所有行分隔的數字和文字? –

回答

0
public static void readAndPrintWholeFile(String filename) throws FileNotFoundException { 
    String fileContents; 
    File file = new File(filename); 
    Scanner scanner = new Scanner(new FileInputStream(file)); 
    Map<String, String> map = new HashMap<>(); 

    while (scanner.hasNextLine()) { 
     try { 
      fileContents = scanner.nextLine(); 
      String[] as = fileContents.split(" +"); 
      map.put(as[0], as[1]); 
      System.out.println(as[0] + " " + as[1]); 
     } catch (ArrayIndexOutOfBoundsException e) { 
      //If some problam with File formate e.g. number without word 
     } 
    } 
} 

你可以用很多方式做到這一點,其中一個是聽到的。 赫拉我沒有實現getNumberOnly()getWordsOnly()方法和我D'噸有DLL實現,以便把數據mapHashMap)。

0

您需要將「fileContents」作爲參數傳遞給函數。

public int getNumberOnly(String fileContents) { 
    int lineNumber; 
    //Get position of space 
    int spacePos = fileContents.indexOf(" "); 
    //Get substring from start till first space is encountered. Also trim off any leading or trailing spaces. Convert string to int via parseInt 
    lineNumber = parseInt(fileContents.subString(0,spacePos).trim()); 
    return lineNumber; 
} 

public String getWordsOnly(String fileContents) { 
    String words; 
    int spacePos = fileContents.indexOf(" "); 
    //Get substring from first space till the end 
    words = fileContents.subString(spacePos).trim(); 
    return words; 
} 
相關問題