0

I have two arraylist like this :

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

And I have code java like this :

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

I want to compare value in arraylist find with arraystring kata. The output that I have like this :

saya = 2 
saya = 1
saya = 0
makan = 1
makan = 1
makan = 0

Overall the output is correct. But I want get output of line. I want an output like this :

saya = 2; 
makan = 1;
saya = 1;
makan = 1;
saya = 0;
makan = 0;

Can anyone help me?

2 Answers 2

1

Here you go. :-)
Try this

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just change the location of two lines as

for (int i = 0; i < hasil.size(); i++) {
        for (int k = 0; k < find.size(); k++) {

Complete code as follow

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

1 Comment

This will help you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.