2016-03-15 30 views
-2

所以我有一个数组t和一个数组x。我试图在数组x的索引5处找到数组t的模式“abc”。我也至今写了这个代码,但很失落,为什么这是不工作...试图在Java中的另一个数组中找到一个数组

,我不能同时==在使用任何东西,但而!=我代码,使其更加棘手。 (否则会使用简单的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"); 

    } 
} 
+1

'布尔了'总是假这里,对不对? –

+1

除了Akshay的回答中的错误之外,还有一个很大的问题,通过将't'的定义更改为'char t [] = {'a','b','c','d' };看看你运行它会发生什么。 – ajb

+0

在while循环的帮助下添加if(a == true)。 –

回答

-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); 
       } 
      } 
     } 
    } 
} 

}

你能做到这一点?这很简单!

+2

这个想法是帮助OP找出他犯了什么错误,而不是炫耀你可以解决问题是你自己的方式。无论如何,我认为这个想法是找出一种算法,它适用于任何想要搜索的数组,而不是硬编码的查找'{'a','b','c'}'的算法。 – ajb

+0

这显然是一个班级。如果教师接受这个答案,他们应该被解雇。 – ajb

+1

但是OP已经找到了一个更好的算法。 – ajb

0

你正在犯一个很小的错误。

你是不是在你的条件设置= TRUE:

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

你的代码更改为:

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

试试这个,它会工作。

编辑:

你正在做的另外一个错误是,你保持while循环中的这个条件:

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

将其移出,同时循环和你原来的代码工作正常。

编辑2: 正如,agb指出,我同意代码很容易崩溃,因为缺少检查和任何输入参数的变化t和x可能会给ArrayIndexOutOfBound异常。

+0

改变了,哎呀!仍然不起作用...最后应该打印索引5。 – lesterpierson123

+0

什么是打印? – theLearner

+0

我同意代码容易崩溃,因为缺少检查和任何输入参数的变化t和x可能会给ArrayIndexOutOfBound异常 – theLearner

1

你的代码已经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"); 
    } 
    
相关问题