我想获取“,”的位置,所以我使用了 charAt 函数
下面是代码
public class JavaClass {
public static void main(String args[]){
System.out.println("Test,Test".charAt(','));
}
}
但问题是我收到 StringIndexOutOfBoundException 任何人都可以帮助我为什么我收到此错误
我还想知道如果没有找到“,”,那么返回的值是什么
错误如下
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 44
at java.lang.String.charAt(Unknown Source)
at JavaClass.main(JavaClass.java:5)
最佳答案
charAt
方法需要一个 int
来表示在字符串中查找的从 0 开始的索引。不幸的是,您传入的 char
,
可以转换为 int
, 44
,并且字符串中的字符数少于 45 个,因此会出现 StringIndexOutOfBoundsException
。
您想查找字符串中 ,
的位置吗?那么 charAt
是错误的方法。尝试indexOf
方法代替。
关于java.lang.StringIndexOutOfBoundsException : while using charAt function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19409867/