2017-05-31 43 views
-3

我將比較字母和輸入的字符串。
當輸入字符串與字母字符串匹配時,我將按如下步驟進行操作。
我想不通爲什麼發生StringIndexOutOfBoundsException。
java中的StringIndexOutOfBoundsException getText()

問題在哪裏?

b1.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 

      int vk_1 = t1.getText().length(); 

      Set chk = new LinkedHashSet(); 

      for(i=0;i<vk_1;i++) { 
       chk.add(t1.getText().toLowerCase().charAt(i)); 
      } 

      String result = Arrays.toString(chk.toArray()).replace("[", "").replace(",", "").replace("]", ""); 

      t2.setText(result.replaceAll("\\p{Z}", "")); 

      if(t1.getText().equals("")) { 
       t2.setText("NO KEY"); 
      } 
     } 
    }); 


b2.addActionListener(new ActionListener() { 


     public void actionPerformed(ActionEvent e) { 

      String s = t2.getText(); // aple 
      char p[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; 
      char c[] = new char[s.length()]; 
      for(i=0;i<s.length();i++) { 
       for(j=1;j<=26;i++) { 
        if(p[j]==s.charAt(i)) { 
         continue; 
        } 
       } 
       System.out.println(p[j]); 
      } 
      if(t2.getText().equals("")) t3.setText("no key"); 
     }  
    }); 
+0

是您的代碼編譯? –

+0

@KrishnaKuntala是的,我只上傳了一些源代碼。 –

+0

你正在增加第二個循環中的錯誤變量(我代替j) –

回答

2

Java數組基於零,因此您的循環必須從索引0開始並運行至長度爲1。

for(j=0;j<26;j++) { 

更好的辦法是使用p.length而非固定值26:

for(j=0;j<p.length;j++) { 

第二個問題是您使用i++代替j++

+0

仍然無法解決。 –

+0

我已確認您的更新答案。 但是,問題沒有解決。 我也附上了我輸入的't2'文本字段源代碼。 請檢查並確認它在哪裏。 –

+0

@mina_star在哪行中出現錯誤? – Jens