我创建了一个Java方法,当传递两个字符串x和y数组时,计算每个字符串在y中出现的次数,并按照字符串在y中出现的顺序打印结果。例如,看看main函数,它应该输出为ab: 2,dc: 1,ef: 0。我的代码不工作,因为它输出ab: 1,ab: 2,dc: 3。
public class stringOccurInArray {
public static void stringOccurInY(String[] x, String[] y) {
int count = 0;
for(int i=0; i<x.length; i++) {
for(int j=0; j<y.length; j++) {
if(y[j].contains(x[i])) {
count++;
System.out.println(y[j] + ": " + count);
}
}
}
count = 0; // reset the count
}
public static void main(String[] args) {
String[] a = {"ab", "cd", "ab", "dc", "cd"};
String[] b = {"ab", "dc", "ef"};
stringOccurInY(a, b);
}
}发布于 2013-06-23 17:35:31
进行以下修改以使其正常工作:
x和y在for环路中。count,以避免重复初始化它。公共类stringOccurInArray { public static void ( String[] x,String[] y) { for(int i=0;i
https://stackoverflow.com/questions/17259365
复制相似问题