我試圖將沒有空格的句子分成3個單詞集。以下是句子。我的代碼的For循環錯誤?
MyNamePanBokVa
以下是我的代碼
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
//String[] listOfWords = request.getParameter("wordList").trim().split("\n");
//int percentage = Integer.parseInt(request.getParameter("percentage"));
PrintWriter pw = response.getWriter();
int numberOfKnownWords = 0;
//Read the Hash File
String str = "";
File inputFile = new File("C:/Users/xxx/Desktop/Test.txt");
HashSet<String>set = new HashSet<String>();
BufferedReader br = new BufferedReader(new FileReader(inputFile));
while((str=br.readLine())!=null)
{
int lastIndex = 0;
for(int i=0;i<=str.length();i=i+3)
{
try
{
String stringPiece = str.substring(i, i+3);
lastIndex = i;
pw.println(stringPiece);
}
catch(Exception arr)
{
String stringPiece = str.substring(lastIndex, str.length());
pw.println(stringPiece);
}
}
}
}
不幸的是這會產生以下輸出。
MyN
ame
Pan
Bok
BokVa
這是應該的,
MyN
ame
Pan
Bok
Bok
Va
我想有一個錯誤在我的for循環,但我無法發現它。這裏有什麼問題?
你怎麼能指望兩次'Bok'的回報? – Aquillo
您是否嘗試過逐步調試代碼?應該清楚問題在哪裏。 – assylias
在預期的輸出中,這不應該是'My'和'Name'而不是'MyN'和'ame'嗎? –