我创建了一个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:36:47
有几件事要提一下。像这样重写你的代码会更容易:
public static void stringOccurInY(String[] x, String[] y) {
int count = 0;
for (int i = 0; i < y.length; i++) {
for (int j = 0; j < x.length; j++) {
if (y[i].contains(x[j])) {
count++;
}
}
System.out.println(y[i] + ": " + count);
count = 0; // reset the count
}
}你应该首先迭代y。
你也可以通过foreach循环来代替迭代。
for (String aY : y) {
int count = 0;
for (String aX : x) {
if (aY.contains(aX)) {
count++;
}
}
System.out.println(aY + ": " + count);
//no need to reset the count
}发布于 2013-06-23 17:33:43
在循环外部定义int j = 0,然后将System.out.println(y[j] + ": " + count);移到第一个for循环外部,并在外部for循环的第一行中将count重置为0。
顺便说一句,你为什么不使用String#equals
发布于 2013-06-23 17:34:03
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
}
}https://stackoverflow.com/questions/17259365
复制相似问题