當我運行我的代碼,輸出是這樣的:寫入/讀取文件和異常
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());
}
}
}
你需要嘗試。我們不是家庭作業服務。如果你想支付我,但我會爲你做! – 75inchpianist
@ 75inchpianist - 聽起來像是嘗試過 - 看到第二個pastebin鏈接。 – Krease