用于确定字符串是否为十六进制数的递归方法 - Java

Joe*_*hez 3 java methods recursion hex

这是一个功课问题,我遇到了一些麻烦.

编写一个递归方法,确定String是否为十六进制数.为您的方法编写javadocs.如果每个字符为0或1或2或3或4或5或6或7或8或9或a或A或b或B或c或C或d或D或e,则字符串为十六进制数字或E或f或f.

目前,我只能看到测试这个,如果字符串0处的字符是他给我的这些值中的一个,那么它的一部分是十六进制.

任何提示或建议,以帮助我?

这是我到目前为止:`

public boolean isHex(String string){


    if (string.charAt(0)==//what goes here?){
        //call isHex again on s.substring(1)
    }else return false;
    }
Run Code Online (Sandbox Code Playgroud)

`

cor*_*iKa 5

如果您正在寻找一个好的十六进制数字方法:

boolean isHexDigit(char c) {
    return Character.isDigit(c) || (Character.toUpperCase(c) >= 'A' && Character.toUpperCase(c) <= 'F');
}
Run Code Online (Sandbox Code Playgroud)

提示或建议,如要求:

  1. 所有递归方法都使用不同的输入调用自己(好吧,希望是不同的输入!)
  2. 所有递归方法都有一个停止条件.

您的方法签名应该看起来像这样

boolean isHexString(String s) {
    // base case here - an if condition

    // logic and recursion - a return value

}
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记十六进制字符串可以以"0x"开头.这可能(更)难以做到,所以我会先让常规函数工作.如果你稍后解决它,请记住0xABCD0x123不应该通过.:-)

关于substring:直接来自String类源:

public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
    throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
    throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
    throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
    new String(offset + beginIndex, endIndex - beginIndex, value);
}
Run Code Online (Sandbox Code Playgroud)

offset是类型的成员变量 int

value是类型的成员变量 char[]

它调用的构造函数是

String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
Run Code Online (Sandbox Code Playgroud)

它显然是一个O(1)方法,调用O(1)构造函数.它可以这样做,因为String是不可变的.您无法更改String的值,只能创建一个新值.(让我们省略反思之类的东西,sun.misc.unsafe因为它们是无关紧要的解决方案!)因为它无法改变,你也不必担心其他一些Thread搞乱它,所以像村里的自行车一样四处传播是完全可以的.