2014-01-10 78 views
-2

當我運行我的代碼,輸出是這樣的:寫入/讀取文件和異常

4 went down to the market 
0 where she bought herself 
1 
0 kitten 
0 she thought the 
6 was 
0  precious, 
2 she 
0 named the kitten 
String index out of range: -1 

但所需的輸出被假設是這樣的

0 Lisa went down to the market 
3 where she bought herself 
0 a 
1 kitten 
2 she thought the 
0 kitten was 
5 precious, 
0 so she 
2 named the kitten 
0 Princess 

我被賦予了文本文件,http://pastebin.com/h51eh8EX,其中包含文本行。我必須編寫一個類來讀取文本,計算每行開始處的空格數,並在每行的開始處寫入行以刪除空格,並用存在的空白數替換它們。

你能解釋一下我的問題嗎?

下面是代碼:

import java.io.File; 
import java.io.IOException; 
import java.util.Scanner; 

public class Squeeze { 
    String fname;//name of the file that contains text to be squeezed 

    /** 
    * Constructor to initialize fname 
    * @param name - name of the file to be squeezed 
    */ 
    public Squeeze(String name) 
    { 
      //TODO Your code goes here 
      fname = name; 
    } 
    /** 
    * Method to remove and count any extra 
    * leading spaces 
    * 
    */ 
    public void squeezeText() 
    { 
      //TODO Your code goes here 
      try 
    { 
     File file = new File("squeeze.txt"); 
     Scanner in = new Scanner(file); 
     while (in.hasNext()) 
     { 

      String line = in.nextLine(); 
      int count = line.substring(0, line.indexOf(" ")).length(); 
      line = count + line.substring(line.indexOf(" ")); 
      System.out.println(line); 
     } 
     in.close(); 
    } 
    catch(Exception e) 
    { 
     System.out.println("Error: " + e.getMessage()); 
    } 

    } 
} 
+4

你需要嘗試。我們不是家庭作業服務。如果你想支付我,但我會爲你做! – 75inchpianist

+0

@ 75inchpianist - 聽起來像是嘗試過 - 看到第二個pastebin鏈接。 – Krease

回答

0

您的計數方法是關閉的,它可能比較容易剛過字符循環。這裏是你可以做到這一點的一種方式 -

while (in.hasNext()) { 
    String line = in.nextLine(); 
    int count = 0; 
    for (char c : line.toCharArray()) { 
    if (c == ' ') { 
     count++; 
    } 
    } 
    line = count + " " + line; 
    System.out.println(line); 
} 
0

嘗試使用正則表達式

while (in.hasNext()) 
{ 
    String line = in.nextLine();  
    Pattern p = Pattern.compile("^\\s+\\w"); 
    Matcher m = p.matcher(line); 
    if (m.find()) { 
      System.out.println(m.group().length() - 1 + " " + line); 
    } else { 
      System.out.println("0" + " " + line); 
    } 
}