【发布时间】:2015-03-01 17:47:49
【问题描述】:
我必须做一个方法来判断一个像 {'d','e','f'} 这样的 char[ ] 数组是否在另一个像 {'a','b 这样的 char[ ] 数组中','c','d','e','f','x','r'} ... 所以,我希望我的“x”在里面,而当找到一个字母时 cicle 会升起。例如,当 for 循环找到第一个字母 my x= 1 时,如果 for 循环找到第二个字母 my x = x+1 等等......所以我的 x 应该等于数组的长度 {'d ','e','f'} 。而如果我必须在像 {'a','d','z','x'} 这样的另一个数组中找到像 {'d','e','f'} 这样的数组,我的 x 是 1 所以它不等于数组 {'d','e','f'} 的长度, 有问题,但我找不到错误。
public class Stringa
{
private char[] array1 ;
public int find2(char[]subs)
{
int x = 1 ;
for(int i=0 ; i<this.lunghezza(); i++ ) // lunghezza() find the length
{
if(this.array1[i] == subs[0])
{
for ( int k = 1 ; k< subs.length ; k++)
{
while (this.array1[i+k]== subs[k])
{
x = x+1; ;
}
}
}
}
return x;
}
}
主要方法是:
public class StringaTester
{
public static void main(String[] args)
{
char[] char1 = {'a','b','c','d','e','f','g','e','r','t'};
char[] char2 = {'a','b','c','d','e','f','g','e','r','t'};
char[] char3 = {'d','e','f'};
Stringa prova = new Stringa(char1);
Stringa prova1 = new Stringa(char2);
Stringa prova3 = new Stringa(char3);
int l = prova3.lunghezza(); // this find the legth of the substring ( Now 3 )
if(char1.find2(char3) == l ) // I want to compare 2 char , but is here the error
// if i write if(prova.find2(char3) == l )
// there aren't any errors
System.out.println(" substring is inside");
else
System.out.println("substring is not inside");
}
}
这是我写 if(char1.find2(char3) == l) 时终端上的错误:
StringaTester.java:20: error: cannot find symbol
if(char1.find2(char3) == l )
^
symbol: method find2(char[])
location: variable char1 of type char[]
1 error
【问题讨论】:
-
好吧,每当您在第一个字母之后找到匹配的字母时,您都会增加
x- 您没有找到任何第二个字母,因此x有其原始字母值为 1。 -
基本上,代码似乎完全按照我的预期工作,但您的要求很难理解。您希望
{'a', 'd', 'z', 'x' }的返回值是多少?{'a', 'd', 'e', 'f', 'd', 'e', 'f' }呢? -
@MightyPork:批评原始缩进是一回事 - 但没有必要以冒犯的方式这样做。
-
@JonSkeet 不要认为这是冒犯性的。如果我在我必须维护的代码中看到类似的东西,我会更生作者的气。
-
"有问题但是..." 你怎么知道有问题?您收到错误消息吗?讯息是什么?此外,您的示例使用了您没有向我们展示任何定义的变量和函数。当我们看不到所有代码时,很难说代码出了什么问题,而且我们不知道症状是什么。
标签: java arrays for-loop while-loop char