java – Method that doesn't work

Question:

The problem is very simple. I have the following exercise:

1- Make a program that requests a text by keyboard and also requests a word to search for, once the data has been entered, the program must show how many times the word to search for appears in the text that has been entered, regardless of whether the word is in uppercase or lowercase. Define a method that returns the number of occurrences of the word to search for.

And although my little expert eye does not find the error, my program does not work no matter how many times I give it. If someone more experienced could give me a hand, I would be very grateful.

package ejercicio1;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;

public class CuentaPalabras {

    public static void main(String[] args) {
        int contador = 0;;
        Scanner sc = new Scanner(System.in);
        System.out.println("Introduzca un texto: ");
        String texto = sc.nextLine().toLowerCase();
        ArrayList<String> textoAr = new ArrayList<String>(Arrays.asList(texto.split(" ,.-_"))) ;
        System.out.println("Introduzca palabra a contar: ");
        String acontar = sc.nextLine().toLowerCase();
        //System.out.println(textoAr);
        for(String palabra : textoAr) {
            contador += Contador(palabra, acontar);
        }
        System.out.println(contador);

    }

    public static int Contador(String palabra, String acontar) {
        if(palabra == acontar) {
            return 1;
        }else {
            return 0;
        }
    }
 }

Answer:

You have a problem when filling the textoAr array with split() , since you are saving the entire phrase, in a single position, that means that when you want to compare, you are comparing a word with the entire phrase, so that is why they do not match:

 System.out.println(textoAr.get(0));

Result

Hi I'm a phrase

In fact, if you print the total size of the textAr array :

System.out.println(textoAr.size()); //Resultado 1, guarda en una sola posición la frase completa

The result is 1

Now, what happens is that it is failing to separate the characters, since within the split the symbols must be inside a bracket like so:

ArrayList<String> textoAr = new ArrayList<String>(Arrays.asList(texto.split("[ ,.-_]")));

In this way, if there is a space or any of the other signs that are inside the brackets, it will separate the word from the rest and store it in a different position in the array .


Also you are not taking how many times the word is repeated correctly, you have a counter and you are not using it correctly:

 //todos los métodos tienen que comenzar en minúscula
public static int contador(String palabra, String acontar) {
    if(palabra.equalsIgnoreCase(acontar)) { 
    //debe ser con equals o equalsIgnoreCase, ya que es texto
        return 1;
    }else {
        return 0;
    }
}

SeeRegular Expressions

Scroll to Top