有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尝试在Java中的另一个数组中查找数组

我有一个数组t和一个数组x,我试图在数组x中找到数组t的模式“abc”,它在数组的索引5处。到目前为止,我已经写了这段代码,但我不明白为什么这不起作用

此外,除了while!=<在我的代码中,eem>或while==,这让它有点棘手。(否则会使用简单的for循环)

有什么想法吗

public static void main(String[] args){


  char t[]={'a','b','c'};
  char x[]={'e','a','b','x','c','a','b','c'};
  int i=0, j=0, c=0;
  boolean a = false;
  while(i != x.length){
      if(t[0]!= x[i]){
          i++;
          continue;
      }
      else{
          j=0;
          while(j != t.length){
              if(t[j]==x[i+j])
              c++; j++;
          }
      if(c==t.length){
         a = true;
          break;
      }
      else{
          i=i+c-1;    
          c=0;
      }
  }
  if (a == true)
  System.out.println("index: "+i); 
  else
  System.out.println("Match not found");

  }
}

共 (3) 个答案

  1. # 1 楼答案

    你犯了一个很小的错误

    在您的情况下,您没有设置a=true:

    if(c==t.length){
        break;
    }
    

    将代码更改为:

    if(c==t.length){
        a = true;
        break;
    }
    

    试试这个,它会有用的

    编辑:

    您所犯的另一个错误是,在循环时将此条件保持在内部:

    if (a == true)
      System.out.println("index: "+i); 
      else
      System.out.println("Match not found");
        }
    

    将其移出while循环,您的原始代码就可以正常工作

    编辑2: 正如agb所指出的,我同意代码容易崩溃,因为缺少检查,输入参数t和x的任何更改都可能导致ArrayIndexOutOfBound异常

  2. # 2 楼答案

    你的代码有2-3个问题

    1. boolean a从未使用过

    2. 条件检查在while循环中(因此,在中断时,不会检查条件)

    3. 还应检查数组x的长度

      char t[] = {'a', 'b', 'c'};
      char x[] = {'e', 'a', 'b', 'x', 'c', 'a', 'b', 'c'};
      int i = 0, j, c = 0;
      boolean a = false;
      while (i != x.length) {
          if (t[0] != x[i]) {
              i++;
          } else {
              j = 0;
              while (j != t.length && i+j<x.length) {
                  if (t[j] == x[i + j]) {
                      c++;
                  }
                  j++;
              }
              if (c == t.length) {
                  a = true;
                  break;
              } else {
                  i = i + c - 1;
                  c = 0;
              }
          }
      
      }
      if (a) {
          System.out.println("index: " + i);
      } else {
          System.out.println("Match not found");
      }
      
  3. # 3 楼答案

    public class Main {
    public static void main(String[] args){
        char t[] = {'a', 'b', 'c'};
        char x[] = {'e', 'a', 'b', 'x', 'c', 'a', 'b', 'c'};
    
        int count = 0;
        while(count != x.length){
            if(x[count] != 'a'){
                count++;
            }else{
                if(x[count + 1] != 'b'){
                    count++;
                }else{
                    if(x[count + 2] != 'c'){
                        count++;
                    }else{
                        System.out.println(count);
                        System.exit(0);
                    }
                }
            }
        }
    }
    

    }

    你能做到吗?这要简单得多