Java 文本编辑器中“查找并替换文本”按钮中的错误

Java 文本编辑器中“查找并替换文本”按钮中的错误,java,Java,我在我的文本编辑器中尝试了“查找并替换”按钮的这种编码,但不起作用 public void actionPerformed(ActionEvent ae) { String findwhat = new String(""); String replacewith = new String(""); String text = ta.getText(); findwhat = textField1.getText(); ln = fi

我在我的文本编辑器中尝试了“查找并替换”按钮的这种编码,但不起作用

public void actionPerformed(ActionEvent ae)
{
    String findwhat = new String("");

    String replacewith = new String("");

    String text = ta.getText();        

    findwhat = textField1.getText();
    ln = findwhat.length();

    replacewith = textField2.getText();

    if (ae.getSource() == findButton)
    {
        startindex = text.indexOf(findwhat, i);

        ta.select(startindex, startindex + ln);

        i = startindex + ln;            
    }        
    else if (ae.getSource() == replace)
    {
        ta.replaceRange(replacewith, startindex, startindex + ln);
    }        
    else if (ae.getSource() == replaceall)
    {
        while (startindex + ln != -1)
        {
            startindex = text.indexOf(findwhat, i);

            ta.replaceRange(replacewith, startindex, startindex + ln);                
        }
    }
}

有人能帮我一下吗???

您的循环使用的变量i似乎没有在您发布的代码中定义。但这不是这里也不是那里。主要问题是条件startIndex+ln!=-1不是测试环路终止的适当条件。您还有另一个问题:如果“查找”和“替换”文本的长度不同,则每次要替换的偏移量都不会是startindex。请尝试此未经测试的循环:

startIndex = text.indexOf(findwhat);
int delta = replacewith.length() - ln;
int deltaOffset = 0;
while(startindex != -1) {
    ta.replaceRange(replacewith, startindex+deltaOffset, startindex+deltaOffset+ln);
    deltaOffset += delta;
    startindex = text.indexOf(findwhat, startindex + ln);
}

如果findtext为空,您还应该拒绝查找并替换或替换所有请求。

如果您有一个无限循环,我相信您的问题将归结为这个while循环:

while (startindex + ln != -1)
{
    startindex = text.indexOf(findwhat, i);

    ta.replaceRange(replacewith, startindex, startindex + ln);                
}
您的代码正在检查以下情况:

while (startindex + ln != -1)
这种情况没有多大意义,因为它说:

while the sum of my current start index and the length of the string I 
am searching for does not equal -1, continue searching.
您在while循环中更新startindex,但我认为它永远不会小于0。即使将其设置为0或-1,您的ln变量也永远不会更新,并且将始终大于-1,因此这将始终为真,并且您永远不会脱离循环

独立地检查每个值更有意义

也许您需要满足以下条件:

while (startindex != -1 && ln > 0)
也就是说:

while I have a startindex to look from (startindex != -1) 
AND 
the string I am looking for is not empty (ln > 0), 
continue to look for the string.

不工作是相当模糊的。它以什么方式不起作用?它会引发异常吗?当它应该做某事的时候什么也不做?做错事?还有什么?你说它不工作是什么意思?这个代码是做什么的?你的工作在哪里?你需要解释什么不起作用。你期望它做什么,为什么?当单击“全部替换”按钮时,它实际上在运行一个无限循环。ta是什么类型?replaceRange方法在哪里?