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;
}
}
}
You have a problem when filling with
split()
thearray
textoAr
, since it is saving the complete 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:Result
In fact, if you print the total size of the
array
textAr
:Now, what happens is that it is failing to separate the characters, since within it
split
the symbols must be inside a bracket such as this: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 save 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:
See Regular Expressions
You could use the following solution:
Try using this method
This method works by storing in the Index variable the position at which it begins to search, when it finds the word it adds one to the occurrences variable and sets the Index to the position where it found the word plus the size of the word so that it begins to search for the word. next appearance from there
You can use an Apache library called Apache Commons Lang. This library has a series of methods to work with String that make life easier on a day-to-day basis. For your case you can use StringUtils.countMatches .
This method is passed the text to search for and the string to search for and returns the number of occurrences that the text has.
Your code would look like this: