zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java实现数字的值返回

JAVA 实现 数字 返回
2023-09-14 08:58:09 时间

以下的静态方法实现了:把串 s 中第一个出现的数字的值返回。
如果找不到数字,返回-1
例如:
s = “abc24us43” 则返回 2
s = “82445adb5” 则返回 8
s = “ab” 则返回-1

/*

*/
public class Demo09_FirstNum {
public static int getFirstNum(String s)
{
if(s==null || s.length()==0) return -1;
char c = s.charAt(0);
if(c>='0' && c<='9') return c-'0'; //填空
return getFirstNum(s.substring(1)); //填空
}
public static void main(String[] args){
String s = "abc24us43";
System.out.println(getFirstNum(s));
}
}

运行结果:
2