我正在做家庭作业,但陷入了 do/while 循环。可能我还没有太多理解,因为我还在学习。
我应该获得字符串其余部分中第一个字符的频率。 例如:我正在服用Infosys;频率为2:
public static void main(String[] args) {
String Input = "";
int count = 0;
do {
char fChar = Input.charAt(0);
for (int i = 0; i < Input.length(); i++)
if (Input.charAt(i) == fChar) {
System.out.println("counter:" + count);
count += 1;
Input = JOptionPane.showInputDialog("Enter Input");
} else System.out.println("Its empty");
} while (!Input.equals(""));
}
我得到:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
我正在尝试,但我知道我在某个地方犯了错误,我想我会请你们帮助我找到我的错误。谢谢
最佳答案
问题是您将 ""
分配给 String
,然后尝试检查 Input.charAt(0)
是否为空。
String input;
int count = 0;
do {
input = JOptionPane.showInputDialog("Enter Input");
char firstChar = input.charAt(0);
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == firstChar) {
count++;
}
}
System.out.println(count);
count = 0;
} while (!input.isEmpty());
注意:您仍然需要检查字符串是否为空,否则会抛出错误。
关于Java 使用 Do/While 循环计算输入文本中第一个字符的出现频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47057954/