我有一個字符串數組toFile[]
,我嘗試寫入文本文件。在測試過程中,我被提醒,如果刺痛達到窗口邊界,記事本不會將字符串包裝到下一行。作爲一名完美主義者,我想將字符串拆分爲長度爲250個字符的子字符串,並將每個字符串寫入文件,在每個子字符串之後打破新行。需要幫助將字符串寫入文本文件中的多行
測試時,我遇到的問題似乎無法解決,是因爲我的程序會一次運行循環,然後失敗並顯示錯誤。
輸出和錯誤的一個例子:
toFile[2].length = 2432
temp.length = 250
split = 250
iLength = 2182
temp.length = 0
split = 500
iLength = 1932
java.lang.StringIndexOutOfBoundsException: String index out of range: -250
我的代碼:
System.out.println("toFile[2].length = "+Integer.toString(toFile[2].length()));
System.out.println("");
if(toFile[2].length()>250){
int iLength=toFile[2].length(), split = 0;
while(iLength>250){
String temp = toFile[2];
temp = temp.substring(split, 250);
System.out.println("temp.length = "+Integer.toString(temp.length()));
bw.write(temp);bw.newLine();
split=split+250;
System.out.println("split = "+Integer.toString(split));
iLength=iLength-250;
System.out.println("iLength = "+Integer.toString(iLength));
System.out.println("");
}
bw.write(toFile[2].substring(split));
}else{bw.write(toFile[2]);bw.newLine();}
bw.newLine();
我也試着穿過整個串運行,但仍然只寫入字符串到一個這個while循環line:
int iLength=toFile[2].length(), start = 0;
String temp = toFile[2];
while(iLength>250){
bw.write(temp,start,250);
start=start+250;
System.out.println("start = "+Integer.toString(start));
iLength=iLength-250;
System.out.println("iLength = "+Integer.toString(iLength));
System.out.println("");
}
你需要一個嵌套循環(所以總共兩個循環)。外層循環遍歷數組中的所有字符串toFile。內循環計算字符數爲250. – markspace 2014-09-11 01:37:49
@markspace數組只包含9個字符串。在這9個,我只需要檢查一些長度。 – TehNoiseBomb 2014-09-11 01:57:28
你仍然需要兩個循環。嘗試製作一種除了將字符串分割爲所需長度以外別無它法的方法。它會幫助你將問題分解成更小的問題。然後調用該方法來檢查需要檢查的字符串。 – markspace 2014-09-11 03:12:03