public class getChar { /**
* @param args
* @throws IllegalArgumentException
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
char[] a={'d','d','g'};
char[] b=null;
try {
System.out.println(new getChar().getchar(b,'k'));
} catch (IllegalArgumentException e) {
// TODO 自动生成 catch 块
System.out.println("参数数组不合法");
} }
public int getchar(char[] a,char b) throws IllegalArgumentException{
if(a!=null){
for(int i=0;i<a.length;i++){
if(a[i]==b)
return i;
}
return -1;
}
else
new IllegalArgumentException();
return -2;
} }class IllegalArgumentException extends Exception{ /**
*
*/
private static final long serialVersionUID = -1120831576794296150L;
}
程序主要实现getchar(char[] a,char b) 方法,这个方法搜索一个字符数组中是否存在某个字符,如果存在,则返回这个字符在字符数组中第一次出现的位置(序号从0开始计算),否则,返回-1。如果传入的数组为null,应抛出IllegalArgumentException异常。我自己再写的时候想getchar方法传入为null数组时应该抛出一个异常,但是Eclipse提示又必须给方法指定一个返回值。
/**
* @param args
* @throws Exception
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws Exception {
// TODO 自动生成方法存根
char[] a = { 'd', 'd', 'g' };
char[] b = null;
ThrowExceptionTest tet = new ThrowExceptionTest();
int returnInt = tet.getchar(b, 'k');
if(-1 == returnInt){
throw new MyIllegalArgumentException();
}
} public int getchar(char[] a, char b) throws IllegalArgumentException {
if (a != null) {
for (int i = 0; i < a.length; i++) {
if (a[i] == b)
return i;
}
}
return -1;
}}class MyIllegalArgumentException extends Exception { private static final long serialVersionUID = -1120831576794296150L;
public static void main(String[] args) {
System.out.println("传递的参数出错了..");
}
}
if (a != null) {
for (int i = 0; i < a.length; i++) {
if (a[i] == b)
return i;
}
return -1;
} else
throw new IllegalArgumentException(); }
这样不就行了?