java - JOptionPane 未返回正确的值

标签 java swing joptionpane

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

这应该运行,打开一个窗口,要求我输入一个字符串,在本例中是一个单词,然后打开另一个窗口,要求我输入另一个字符串,在本例中是一个字母。然后,它获取第二个字符串(字母)并尝试查找该字母在第一个字符串(单词)中出现的次数。

例如,我编译,然后运行。运行后,它会打开一个窗口,我输入单词 cat,然后打开第二个窗口,我输入字母 A。我得到一个返回窗口,告诉我字母 A 在单词 cat 中出现了 0 次。这就是发生的事情,现在我只是得到字符串越界异常字符串索引超出范围: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);
   }
}

有人知道出了什么问题吗?

最佳答案

问题在于以下代码块,您在 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++;
    }
}

关于java - JOptionPane 未返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59257877/

相关文章:

Java:JOptionPane 对象的属性是什么,可以防止在其下方单击?

java - 使用 PriorityBlockingQueue 时出现 ClassCastException

java - 是否可以阻止一次触发 Action 监听器?

java - 如何从 XML 解析中正确显示内容?

java - 使用 GridLayout 将按钮添加到框架

java - 在处理之前禁用框架

java - JTable:WAITING根据用户输入选择行

java - JDialog 在执行 'dispose' 之前不显示

java - 每个子类继承关系表 : How to query against the Parent class without loading any subclass ? ?? ( hibernate )

java - 将函数从返回 long 更改为 BigInteger