JOptionPane未返回正确的值

时间:2019-12-09 23:01:00

标签: java swing joptionpane

不允许使用数组,该函数正在运行,但仅返回0,就好像它没有在计算正确的输入字符一样,但是现在它给了我一个“超出范围的字符串:3”

这应该运行,打开一个窗口,要求我输入一个字符串,在这种情况下,它是一个单词,然后打开另一个窗口,要求我输入另一个字符串,在这种情况下,这是一个字母。然后,它使用第二个字符串(字母),并尝试找出该字母在第一个字符串(单词)中出现了多少次。

例如,我编译然后运行。运行之后,它将打开一个窗口,我输入单词cat,然后打开第二个窗口并输入字母A。我得到一个返回窗口,告诉我字母A在单词cat中出现0次。这就是WAS发生的事情,现在我只是使字符串超出范围,异常字符串索引超出范围:3

import javax.swing.JOptionPane; // Need for JOptionPane

/*
   This program is used to
   get a word and a letter 
   from the user and count 
   and display the number of
   times the letter appears 
   in the word.
*/

public class LetterCounter {

   public static void main(String[] args) {

   String userInput;
   String userSentence;
   char userChar;
   int charCount = 0;
   int index = 0;

   userInput = JOptionPane.showInputDialog("Enter a String: ");
   userSentence = userInput;

   userInput = JOptionPane.showInputDialog("Enter a Character: ");
   userChar = userInput.charAt(0);

   for(index = 0; index < userSentence.length(); index++);   {
       if(userSentence.charAt( index ) == userChar) {
          charCount++;
       }
    }
    JOptionPane.showMessageDialog(null, userChar + " is used in "
                                    + userSentence + "  " + charCount +
                                    " time(s).");


    System.exit(0);
   }
}

有人知道怎么了吗?

1 个答案:

答案 0 :(得分:1)

问题在于以下代码块,其中您在;循环之后放置了for

for(index = 0; index < userSentence.length(); index++);   {
   if(userSentence.charAt( index ) == userChar) {
      charCount++;
   }
}

只需按照以下步骤将其删除,即可正常使用

for (index = 0; index < userSentence.length(); index++) {
    if (userSentence.charAt(index) == userChar) {
        charCount++;
    }
}