我有两个这样的数组列表:
ArrayList<String> hasil = new ArrayList<String>();
hasil.add("saya makan saya");
hasil.add("makan kamu dimana saya");
hasil.add("kamu dimana");
ArrayList<String> find = new ArrayList<>();
find.add("saya");
find.add("makan");
我有这样的代码java:
String[] kata = new String[10];
for (int k = 0; k < find.size(); k++) {
for (int i = 0; i < hasil.size(); i++) {
kata = hasil.get(i).split(" ");
for (int j = 0; j < kata.length; j++) {
if (kata[j].equals(find.get(k))) {
c++;
}
}
System.out.println(find.get(k) + " = " + c);
c = 0;
}
}
我想将数组列表查找中的值与数组字符串 kata 进行比较。我有这样的输出:
saya = 2
saya = 1
saya = 0
makan = 1
makan = 1
makan = 0
总体而言,输出是正确的。但是我想得到行的输出。我想要这样的输出:
saya = 2;
makan = 1;
saya = 1;
makan = 1;
saya = 0;
makan = 0;
谁能帮我?
你去吧。 :-(
试试这个
String[] kata = new String[10];
for (int i = 0; i < hasil.size(); i++) {
for (int k = 0; k < find.size(); k++) {
kata = hasil.get(i).split(" ");
for (int j = 0; j < kata.length; j++) {
if (kata[j].equals(find.get(k))) {
c++;
}
}
System.out.println(find.get(k) + " = " + c);
c = 0;
}
}
只需将两行的位置更改为
for (int i = 0; i < hasil.size(); i++) {
for (int k = 0; k < find.size(); k++) {
完整代码如下
public static void main(String[] args) {
System.out.println("Program Start");
int c = 0;
ArrayList<String> hasil = new ArrayList<String>();
hasil.add("saya makan saya");
hasil.add("makan kamu dimana saya");
hasil.add("kamu dimana");
ArrayList<String> find = new ArrayList<>();
find.add("saya");
find.add("makan");
String[] kata = new String[10];
for (int i = 0; i < hasil.size(); i++) {
for (int k = 0; k < find.size(); k++) {
kata = hasil.get(i).split(" ");
for (int j = 0; j < kata.length; j++) {
if (kata[j].equals(find.get(k))) {
c++;
}
}
System.out.println(find.get(k) + " = " + c);
c = 0;
}
}
}