Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java.lang.StringIndexOutOfBoundsException:在使用charAt函数时_Java - Fatal编程技术网

java.lang.StringIndexOutOfBoundsException:在使用charAt函数时

java.lang.StringIndexOutOfBoundsException:在使用charAt函数时,java,Java,我想得到“,”的位置,所以我使用了charAt函数 下面是代码 public class JavaClass { public static void main(String args[]){ System.out.println("Test,Test".charAt(',')); } } 但问题是我得到了StringIndexOutOfBoundException任何人都能帮我解释为什么我会得到这个错误吗 我还想知道,如果没有找到“”,那么返回的值是多少 错误如下

我想得到“,”的位置,所以我使用了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
,而不是
charAt
System.out.println(“Test,Test.indexOf”(“,”)
charAt
仅返回字符串某个位置的字符;在本例中,它将是“,”的ascii码。

如果您查看该方法,您将看到它包含一个
int
参数。当您给
字符时,它会获取该字符的ASCII值(44),并尝试获取该索引处的值,该值恰好远大于字符串的长度。这就是为什么会出现
StringIndexOutOfBoundsException

为此,您需要使用

System.out.println("Test,Test".indexOf(','));

字符(int位置)将输入参数作为整数。“,”等效ascii值44,因此只有您得到异常

阅读
charAt
javadoc并了解基本类型<在该方法调用中,'
被视为
int
<代码>字符串索引超出范围:44应该放弃它。