2023-12-14

How can I check duplicated words within an Array and count them?

I just started programming with JAVA 2 months ago and currently I'm facing an exercise which I don't find the solution for. Until now I control (kind of) the following structures: if (else), do while, while, for, basic array and matrix management, so the exercise is intended to be solved with some of them.

And the exercise says: "Build a simple program that asks for three words and tells you the number of different words or how many are the same. The process will be repeated until one of the words is "exit"." So far this is what I got:

    String [] names = new String [3];

        int index=0;
        boolean found=false;
        int position=0;
        for (int i=0; i<names.length; i++) {
            if (i==0) {
            System.out.println("User, give me name");
            names[i]=lector.nextLine();
            if (names[i].equals("exit")) {
                break;
            }
            } else {
                System.out.println("Give me another name");
                names[i]=lector.nextLine();
                i=position;
                found=false;
                if (names[i].equals("exit")) {
                    break;
                }
                do {
                    if (names[position].equals(names[i-1])) {
                        found=true;

                    }
                    index++;
                } while (position>=0 && !found);
                
            }
        }
        System.out.println("Repeated words: "+index);

So I have to use the scanner and let the user write three words under the previous rules.

I'm talking about arrays as it's the first and only way I find to solve the problem, but there may be others.
I'm getting an out of bounds error and I honestly have no idea what can I do. There are probably other easier and more optimal ways to do it, but as I said the academy expect an answer from us using the "basic" knowledge we have at this point. However, every approach will be a huge help.



No comments:

Post a Comment