A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘士林 中级黑马   /  2012-11-1 10:35  /  1660 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

calss Demo
{
     public static void main(String[] args)
    {
  
         String s = "abc我";
         int x = s.indexOf(99);
         int y = s.indexOf("c");
         int z = s.indexOf('c');
          System.out.println(x);
          System.out.println(y);
          System.out.println(z);
         
        int a = add("a","b");//编译通不过
   }
    public int add(int ch,int ch1)
    {
     
     return(ch+ch1);
    }
}
打印结果为2,2,2
查看api可知,indexOf 的参数为(int ch),但是传进去“c”或者‘c’或者99都可以编译通过,并打印出字符c的角标位2
自定义的add方法参数类型也是int,传进去字符串就不能通过,同样是int型的参数,为什么indexOf的就能通过,
而自定义的就不能通过?


评分

参与人数 1技术分 +1 收起 理由
韩军博 + 1 很给力!

查看全部评分

3 个回复

倒序浏览
indexOf()这个方法有重载的
回复 使用道具 举报
在Java当中char类型是可以匹配int类型的。
s.indexOf(int ch)是可以传入字符作为参数的。是用字符‘c’的ASCII编码来匹配int类型参数。

回复 使用道具 举报
calss Demo
{
     public static void main(String[] args)
    {
  
         String s = "abc我";
         int x = s.indexOf(99);
         int y = s.indexOf("c"); //这里通过是因为String对象中有一个indexOf,参数为String的方法。
         int z = s.indexOf('c'); //这里通过是因为字符占2个字节,int占4个字节,所以传入的字符会自动通过ASCII编码来匹配int类型参数。
          System.out.println(x);
          System.out.println(y);
          System.out.println(z);
         
        int a = add("a","b");//编译通不过
   }
    public int add(int ch,int ch1)
    {
     
     return(ch+ch1);
    }
}

评分

参与人数 1技术分 +1 收起 理由
韩军博 + 1 很给力!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马