2017-10-07 44 views
-1

我有一個文本文件,它看起來像這樣顯示特定行去年和明年3行:如何在一個文件

technology 
education 
medicine 
women 
architecture 
programming 
reading 
coffee 
dog 
cat 
bird 

我需要在這個文件中搜索特定詞(例如「架構'),並獲得前三行和下三行。在上面的文件中,前三行的輸出爲'教育醫學女性',接下來的三行輸出'編程閱讀咖啡'。

我能夠得到接下來的三行,但是,我無法弄清楚如何獲得Java中的前三行。你能幫我解決這個問題嗎?這是我到目前爲止有:

Scanner in = new Scanner(new File(filename)); 
     while (in.hasNextLine()){ 
      String str = in.nextLine(); 
      if (str.indexOf("architecture") !=-1){ 
      //this is where I need the code for getting the previous three 
      //lines to go 

      } 
     } 
+0

如果是「技術」或「鳥」,該怎麼辦? – Ravi

+0

@Ravi我只需要找到'架構'和前三個字和下三個字。 – user3602426

回答

0

如果後architecture之前想的話,那麼可能的解決方案之一是將所有的字存儲到List並獲得architecture的索引,並且取得-3到+3。

List<String> lst = new LinkedList<>(); 
    int indx =0; 
    int count =0; 
    Scanner in = new Scanner(new File(filename)); 
     while (in.hasNextLine()){ 
      String str = in.nextLine(); 
      lst.add(str); 
      if (str.indexOf("architecture") !=-1){ 
      indx=count;// get the index. 
      } 
     count++; 
     } 

現在,檢索它們:

//to avoid accessing out of bound index 
int max = (indx+3) >= count ? count -1 : (indx+3);//maximum index should be T-1. 
indx = (indx - 3) < 0 ? 0 : (indx - 3); // minimum index should be 0. 

for(;indx <= max;indx++) 
{ 
    System.out.println(lst.get(indx)); 
} 

>>>Demo<<<

+0

@ user3602426。請忘記告訴你,任何單詞都很靈活。不要忘記豎起大拇指;) – Ravi

0
  • 從文件中讀取所有行,並將它們存儲在列表中
  • 找到您要尋找的字符串的索引。
  • 按要求的索引打印字符串。

    List<String> lines = Files.readAllLines(Paths.get(filename)); 
    int index = lines.indexOf("architect"); 
    String finalString = lines.get(index-3) + " " + lines.get(index-2) + " " + lines.get(index-1) + " " + lines.get(index+1) + " " + lines.get(index+2) + " " + lines.get(index+3); 
    
+0

如果索引處於開頭或結尾,這可能會導致索引超出限制。 – Ravi

+0

@Ravi,OP必須處理它。他還必須做異常處理。如果他需要,我也可以提供這些細節。 – VHS

0

保持前3行。這裏一個循環法算法:一個數組,其中最舊的元素被覆蓋。

String[] previousLines = new String[3]; 
int previousWritePos = 0; 
int previousCount = 0; 

Scanner in = new Scanner(new File(filename)); 
while (in.hasNextLine()){ 
    String str = in.nextLine(); 
    if (str.indexOf("architecture") !=-1){ 
      //this is where I need the code for getting the previous three 
      //lines to go 
    } 

    // Remember this line as previous line: 
    previousLines[previousWritePos] = str; 
    if (previousCount < 3) { 
     ++previousCount; 
    } 
    previousWritePos = (previousWritePos + 1) % 3; 
} 

for (int i = 0 ; i < previousCount; ++i) { 
    int index = (previousWritePos + 2 - i) % 3; 
    System.out.println("Previous: " + previousLines[index]; 
}