2014-09-29 42 views
-3

我试过这种编码,在我的文本编辑器中查找和替换按钮,但无法正常工作。文本编辑器中的“查找并替换文本”按钮中的错误

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);     
     } 
    } 
} 

有人能帮我吗?

+0

_ “不工作” _是非常模糊的。它以什么方式不起作用?它是否会抛出异常?当它应该做什么时什么也不做?做错了什么?还有别的吗? – 2014-09-29 17:42:22

+0

你是什么意思,“它不工作”?这段代码做了什么?你的[MCVE](http://stackoverflow.com/help/mcve)在哪里? – 2014-09-29 17:42:25

+0

你需要解释什么是不工作。你期望它做什么,为什么?它实际上做的是什么 – 2014-09-29 17:42:46

回答

0

您的循环使用的变量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是空的。

0

我相信你的问题将归结到这个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. 

您更新startindex在while循环中,但我认为它不会小于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.