请在一个类中编写一个方法,这个方法搜索一个字符数组中是否存在某个字符,如果存在,
则返回这个字符在字符数组中第一次出现的位置(序号从0开始计算),否则,返回-1。
要搜索的字符数组和字符都以参数形式传递传递给该方法,如果传入的数组为null,
应抛出IllegalArgumentException异常。在类的main方法中以各种可能出现的情况测试验证该方法编写得是否正确,
例如,字符不存在,字符存在,传入的数组为null等。

解决方案 »

  1.   

    // major codes 
    // char[] array, char c
      return new String(array).indexOf(c);
      

  2.   

    public class SerachChar {
      public static void main(String[] args) {
        SerachChar sc=new SerachChar();
        char c[]={'a','b','c'};
        System.out.println(sc.serach(c,'b'));
        System.out.println(sc.serach(c,'d'));
        System.out.println(sc.serach(null,'a'));
      }
      public int serach(char c[],char ch){
        if(c==null){
          throw new IllegalArgumentException("参数数组c为空");
        }else{
          String str = new String(c);
          int result = -1;
          result = str.indexOf(ch);
          return result;
        }
      }
    }
      

  3.   

    public class find
    {
        public int getResult(char[] array, char c)
        {
            return(new String(array).indexOf(c));
        }
        public static void  main(String args[])
        {
             char[] array={'a','b','c'};
             find f=new find();
             System.out.println(""+f.getResult(array,'c'));
        }
    }我还给了测试数据的结果是2
      

  4.   

    自己回个帖。谢谢大家!
    public class TestSearch
    {
    public int search(char c[],char ch)
    {
    int flag = -1;
    if(c == null)
    {
    throw new IllegalArgumentException("参数数组为空!");
    }
    else
    {
    for(int i=0;i<c.length;i++)
    {
    if(ch == c[i])
    {
    flag = i;
    return flag;
    }
    }
    }
    return flag;

    /*
    if(c==null)
    {
    throw new IllegalArgumentException("参数数组c为空");
    }
    else
    {
    String sc = new String(c);
    int result = -1;
    result = sc.indexOf(ch);
    return result;
    //return(sc.indexOf(ch));
    }*/
    } public static void main(String [] args)
    {
    char [] c = {'a','b','c'};
    TestSearch s = new TestSearch();
    System.out.println(s.search(c,'b'));
    System.out.println(s.search(c,'d'));
    System.out.println(s.search(null,'a'));
    }
    }
      

  5.   

    我有点晕,jdk中有这个方法,到API文档中去看看,想看源码就去src
      

  6.   

    weijieut() :
    我有点晕,jdk中有这个方法,到API文档中去看看,想看源码就去src 什么意思呀,api文挡中怎么看源码啊?
      

  7.   

    虽然楼上的代码都可以说是正确的,但是无一例外的没有考虑java的性能问题。试问,如果数组长度大于1万,使用String对象是否合适?用String,会对这个大数组进行一次复制的。
    不要看到现成的算法就拿来用,算法的使用要考虑一下,应该使用循环自行遍历这个数组,不要使用String。Java本身性能并不是很差,性能差的原因是因为滥用API。