どうしても分からない宿題があります。文字列 x と文字列 y が一致するかどうかのブール値を返す静的メソッド match(String x, String y) を作成する必要があります。マッチング プロセスでは、任意の 1 文字と一致する「@」文字や、任意のタイプの 0 個以上の文字と一致する「*」文字などの「ワイルド カード」を許可する必要があります。ループの使用は許可されておらず、再帰を使用する必要があります。ここまで書いてきたことは…
public class CompareStrings {
public static boolean match(String x, String y) {
if (x.length() <= 1 && y.length() <= 1) {
if (x.equals("*") || y.equals("*")) {
return true;
}
if ((x.length() == 1 && y.length() == 1) && (x.equals("@") || y.equals("@"))) {
return true;
}
return x.equals(y);
}
String x1 = "";
String x2 = "";
String y1 = "";
String y2 = "";
if (x.length() == 0 && y.charAt(0) == '*') {
y2 = y.substring(1, y.length());
}
if (y.length() == 0 && x.charAt(0) == '*') {
x2 = x.substring(1, x.length());
}
if (x.length() > 1 && y.length() > 1) {
if (x.length() != y.length() && !x.contains("*") && !y.contains("*")) {
return false;
}
if (x.charAt(0) == '*') {
x1 = "*";
x2 = x.substring(1, x.length());
y1 = "*";
y2 = y.substring(y.length()-x2.length(), y.length());
}
else if (y.charAt(0) == '*') {
y1 = "*";
y2 = y.substring(1, y.length());
x1 = "*";
x2 = x.substring(x.length()-y2.length(), x.length());
}
else {
x1 = x.substring(0, 1);
x2 = x.substring(1, x.length());
y1 = y.substring(0, 1);
y2 = y.substring(1, y.length());
}
}
return match(x1, y1) && match(x2, y2);
}
public static void main(String[] args) {
System.out.println(match("hello", "hello.") + " 1 false"); // should return false
System.out.println(match("hello", "jello") + " 2 false"); // should return false
System.out.println(match("hello", "h@llo") + " 3 true"); // should return true
System.out.println(match("hello", "h@@@@") + " 4 true"); // should return true
System.out.println(match("hello", "h*") + " 5 true"); // should return true
System.out.println(match("hello", "*l*") + " 6 true"); // should return true
System.out.println(match("anyString", "*") + " 7 true"); // should return true
System.out.println(match("help", "h@@@@") + " 8 false"); // should return false
System.out.println(match("help", "h*") + " 9 true"); // should return true
System.out.println(match("help", "*l*") + " 10 true"); // should return true
System.out.println(match("help", "*l*p") + " 11 true"); // should return true
System.out.println(match("help", "h@llo") + " 12 false"); // should return false
System.out.println(match("", "*") + " 13 true"); // should return true
System.out.println(match("", "***") + " 14 true"); // should return true
System.out.println(match("", "@") + " 15 false"); // should return false
System.out.println(match("", "") + " 16 true"); // should return true
}
}
主なメソッドは、割り当てによって与えられるテスト プログラムです。私のコードが少し乱雑であることに気付きました - 私は少し混乱していました - しかし、私はそれのほとんどを動作させることができます. 正しい値を返さない唯一の例は 11 番です。true であるべきときに false になります。これが起こっていると思う理由は、文字列 y が ' ' で始まるため、 y の最初の ' ' が 2 を表すはずなのに、私のメソッドが x と y の両方の文字列を最後の 3 文字に分割するためです。文字。このようなケースが一致を返すようにするにはどうすればよいですか?