gpt4 book ai didi

java - 方法内的字符串索引超出范围 : Java

转载 作者:太空宇宙 更新时间:2023-11-04 12:09:41 24 4
gpt4 key购买 nike

我正在为我的类编写一些代码,但遇到了这个错误,字符串索引超出范围。我检查了一下是否可能是 string = null 但事实并非如此。我猜这与方法中的 if 语句有关,但我找不到如何在任何地方修复它。感谢任何帮助,非常感谢!

import java.util.*;
public class Occurences {
public static void main(String[] args) {
int check = 0;
char characterInput = ' ';
do {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string: ");
String input = scan.next();
System.out.println("Enter a character to find it's occurence in the string: ");
characterInput = scan.next().charAt(0);
int i = count(input, characterInput);

System.out.println(characterInput + ", is in " + input + ", " + i + " times.");
System.out.println("To continue enter any number, to exit enter -1: ");
check = scan.nextInt();
} while (check != -1);
}
public static int count(String input, char characterInput) {
int cnt = 0;
int j = input.length();
while (j > 0) {
if (input.charAt(j) == characterInput) {
cnt += 1;
}
j--;
}
return cnt;
}
}

最佳答案

错误发生在第 21 行:int j = input.length(),正如其他人在评论中提到的那样,java 和大多数编程语言通过零索引来索引字符串和数组类型 - 从零开始。因此,您必须 1) 从 0 开始计数,或者 2) 在小于字符串(数组)长度的位置停止计数,这就是为什么第 21 行需要是:

int j = input.length()-1;

或者如您使用方法 1 解决的那样:

设置int j=0;

关于java - 方法内的字符串索引超出范围 : Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39968932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com