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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© tfy 中级黑马   /  2012-12-2 12:37  /  1305 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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


* @author Administrator
*
*/

public class Test9 {
                 public static void main(String[] args) {
                 
                  char[] strs={'d','s','g','s','i','y'};
                  int index=searchCharIndex(strs, 'y');
                  if(index==-1){
                   System.out.println("字符不存在");
                  }else{
                   System.out.println("字符的位置为:"+index);
                  }   
                 }
                 
                 
                 public static int searchCharIndex(char[] chars,char c){
                  int index=-1;//要查找的字符在数组中的位置
                  
                  //如果数组为null,则抛出IllegalArgumentException
                  //如果不为null,则开始查找字符在数组中的位置
                  if(chars==null){
                   new IllegalArgumentException().printStackTrace();
                  }else{
                   for (int i = 0; i < chars.length; i++) {
                    if(c==chars[i]){
                     index=i;
                    }
                   }
                  }
                  return index;
                 }
                }



0 个回复

您需要登录后才可以回帖 登录 | 加入黑马