0

我想获得“,”的位置,所以我使用了 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)
4

4 回答 4

5

charAt方法需要一个int表示在字符串中查找位置的基于 0 的索引。对您来说不幸的是,char您传入的 ,,可以转换为int, 44,并且您的字符串中没有 45 个或更多字符,因此StringIndexOutOfBoundsException.

你想找到,你的字符串中的位置吗?然后charAt是错误的方法。试试这个indexOf方法。

于 2013-10-16T17:28:36.423 回答
3

您应该使用indexOf, 而不是charAt System.out.println("Test,Test".indexOf(",")); charAt只返回字符串某个位置的字符;在这种情况下,它将是 ',' 的 ascii 代码

于 2013-10-16T17:28:38.597 回答
1

如果你看一下 method String#charAt(int index),你会发现它接受了一个int参数。当您给出'字符时,它会获取该字符的 ASCII 值(即44)并尝试获取该索引处的值,这恰好比字符串的长度大得多。这就是为什么你得到StringIndexOutOfBoundsException.

您需要为此使用indexOf()

System.out.println("Test,Test".indexOf(','));
于 2013-10-16T17:29:22.183 回答
1

charAt(int position) 将输入参数作为整数。"," 等价的 ascii 值 44 因为这只是你得到的例外。

于 2013-10-16T17:31:51.283 回答