public class TestIndextOf {
public static void main(String[] args) {
String s="abcdef8";
System.out.println(s.indexOf("a"));
System.out.println(s.indexOf(8));
}}
返回结果是:0,-1。请大家给我解释下,为什么第二个返回的是-1,INDEXOF()返回的结果不是从0开始的吗?

解决方案 »

  1.   

    去看看API文档吧,给你复制一下:
    indexOf
    public int indexOf(int ch)返回指定字符在此字符串中第一次出现处的索引。如果在此 String 对象表示的字符序列中出现值为 ch 的字符,
    则返回第一次出现该字符的索引(以 Unicode 代码单元表示)。对于 0 到 0xFFFF(包括 0 和 0xFFFF)范围内的 ch 的值,返回值是 
     this.charAt(k) == ch
     为 true 的最小 k 值。对于其他 ch 值,返回值是 
     this.codePointAt(k) == ch
     为 true 最小 k 值。无论哪种情况,如果此字符串中没有这样的字符,则返回 -1。 
      

  2.   


    public class TestIndextOf { 
    public static void main(String[] args) { 
    String s="abcdef8"; 
    System.out.println(s.indexOf("a")); 
    System.out.println(s.indexOf(8)); 
    } }改成:public class TestIndextOf { 
    public static void main(String[] args) { 
    String s="abcdef8"; 
    System.out.println(s.indexOf("a")); 
    System.out.println(s.indexOf("8")); 
    } }
      

  3.   

    第二个你应该写成indexOf("8") 而不是indexOf(8) 这是两个不同的方法
    第一个方法很好理解 
    第二个方法里的8是ch的值 不是你理解的那个字符串8
      

  4.   

    System.out.println(s.indexOf(8));  //这个是找值
    改成 System.out.println(s.indexOf("8")); //这个是找索引的地址