不允许使用数组,该函数正在工作,但只是返回 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/