我正在尝试将一个没有空格的句子分成 3 个单词的集合。下面是这句话。
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 循环中有一个错误,但我无法发现它。这里出了什么问题?
最佳答案
考虑当 i
位于 V 时的情况。
MyNamePanBokVa
^
我= 12
到目前为止的输出:
MyN
ame
Pan
Bok
{
String stringPiece = str.substring(i, i+3);
//throws exception, lastindex is not updated
lastIndex = i;
}
catch(Exception arr)
{
String stringPiece = str.substring(lastIndex, str.length());
// lastIndex =9 prints BokVa
pw.println(stringPiece);
}
关于java - 我的代码的 For 循环出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21670915/