以下的静态方法实现了:把串s中第一个出现的数字的值返回。
如果找不到数字,返回-1例如:
s = "abc24us43" 则返回2
s = "82445adb5" 则返回8
s = "ab" 则返回-1 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 _____________; //填空
return getFirstNum(______________); //填空
}
如果找不到数字,返回-1例如:
s = "abc24us43" 则返回2
s = "82445adb5" 则返回8
s = "ab" 则返回-1 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 _____________; //填空
return getFirstNum(______________); //填空
}
2. s.substring(1);(使用递归获取其子串,去除已经判断的字符)
public class StringTest
{
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)
{
Scanner input = new Scanner(System.in);
String hex=input.nextLine();
System.out.println("The number is"+getFirstNum(hex));
}
}
c-'0':返回的是用ASCII码计算出的整型;
c:返回字符型数字,会自动类型转换成int型。
第二空:s.substring(1)
已经判断了第一个字符,递归调用方法判断剩余字符串。
普科学生