/*
* 在一个类中编写一个方法,这个方法搜索一个字符数组中是否存在某个字符,如果存在,则返回这个字符在字符数组中第一次出现的位置(序号从0开始计算),否则,返回-1。
* 要搜索的字符数组和字符都以参数形式传递传递给该方法,如果传入的数组为null,应抛出IllegalArgumentException异常。
* 在类的main方法中以各种可能出现的情况测试验证该方法编写得是否正确,例如,字符不存在,字符存在,传入的数组为null等。
*/
public class Text7 {
public static void main(String[] args) {
char ch='f';
char [] ch1={'f','w','g'};
char [] ch2={'w','h','r'};
char [] ch3=null;
System.out.println(find(ch1,ch));
System.out.println(find(ch2,ch));
System.out.println(find(ch3,ch));
}
public static int find(char [] chr,char ch)
{
try{
if(chr==null)
{
throw new IllegalArgumentException();
}
for(int x=0;x<chr.length;x++)
{
if(chr[x]==ch)
return x;
}
}catch(IllegalArgumentException e)
{
System.out.print("请输入正确参数");
}
return -1;
}
} |
|