怎样才能正确跳出递归
public int checkId(String id){
int flag = 0;
char[] c = id.trim().toCharArray();
System.out.println("长度为: "+id.length());
char ch = id.charAt(id.length()-1);
for(int j=0;j<id.length()-1;j++){
if(ch != c[j]){
System.out.println("Array: "+c[j]);
System.out.println("***************可用");
flag = 1;
break;
}else{
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!不可用");
id = id.substring(j+1, id.length());
System.out.println("值为: "+id);
System.out.println("长度为: "+id.length());
checkId(id);
return flag;
}
}
System.out.println("flag的值为: "+flag);
return flag;
}
public static void main(String[] args){
String str = "111121";
if(user.checkId(str) == 1){
System.out.println("可用");
}else{
System.out.println("不可用!");
uid = Integer.parseInt(str.trim())+1;
System.out.println("重新计算的值为: "+uid);
}
}
判断到 2 的时候正常返回了flag的值为 1
但是又返回到递归中继续运行,所以
结果永远为不可用.
还请各位指点下怎样才可以正确跳出,
判断出不同之后不再执行递归.
------解决方案--------------------
public int checkId(String id){
int flag = 0;
char[] c = id.trim().toCharArray();
System.out.println("长度为: "+id.length());
char ch = id.charAt(id.length()-1);
for(int j=0;j <id.length()-1;j++){
if(ch != c[j]){
System.out.println("Array: "+c[j]);
System.out.println("***************可用");
flag = 1;
break;
}else{
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!不可用");
id = id.substring(j+1, id.length());
System.out.println("值为: "+id);
System.out.println("长度为: "+id.length());
flag=checkId(id);
return flag;
}
}
System.out.println("flag的值为: "+flag);
return flag;
}