2015-04-04 44 views
0

我完全停留了幾個小時。用線條間的空白掃描一個較大的文本

說我想在程序中掃描,例如

// my program in C++ 

#include <iostream> 
/** playing around in 
a new programming language **/ 
using namespace std; 

int main() 
{ 
    cout << "Hello World"; 
    cout << "I'm a C++ program"; //use cout 
    return 0; 
} 

我想通過這個輸入,並將其保存在ArrayList<String>

這裏是我的代碼:

public static void main(String[] args) { 
     ArrayList<String> testCase = new ArrayList<String>(); 
     int count = 0; 
     Scanner s = new Scanner(System.in); 
     testCase.add(s.nextLine()); 
     while (s.hasNext() && s.next().length() > 1) { 
      testCase.add(s.nextLine()); 
     } 

     System.out.println("\n\n\n\n----------------Output from loop------------------"); 
     for (String tc : testCase) { 
      System.out.println(tc); 
     }  
    } 

此輸出:

----------------Output from loop------------------ 
// my program in C++ 
<iostream> 
playing around in 

掃描應該如果連續出現2個空行,則停止。

任何幫助,非常感謝。

回答

0

代碼中的問題是您在條件中使用了s.next()。這個方法消耗下一個令牌,這個令牌不再被使用。

我不知道s.next().length() > 1是用來檢查的,但是如果你刪除那部分條件,你會消耗每一行而沒有任何問題。

下面的代碼將掃描的每一行,並停止每當兩個連續的空行得到滿足:

public static void main(String[] args) throws Exception { 
    System.setIn(new FileInputStream("C:\\Users\\Simon\\Desktop\\a.txt")); 
    ArrayList<String> testCase = new ArrayList<String>(); 
    int emptyLines = 0; 
    String line; 
    Scanner s = new Scanner(System.in); 
    testCase.add(s.nextLine()); 
    while (s.hasNext() && emptyLines < 2) { 
     line = s.nextLine(); 
     if (line.isEmpty()) { 
      emptyLines++; 
     } else { 
      emptyLines = 0; 
     } 
     testCase.add(line); 
    } 

    System.out.println("\n\n\n\n----------------Output from loop------------------"); 
    for (String tc : testCase) { 
     System.out.println(tc); 
    } 
}