I need to do a program where the program receives a phrase and then a letter, and then return how many times the letter appears in the sentence. So I did this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Exercicio1_string {
public static void main(String[] args) {
InputStreamReader c = new InputStreamReader(System.in);
BufferedReader cd = new BufferedReader(c);
String frase = "";
String letra = "";
System.out.println("Escreva uma frase: ");
try {
frase = cd.readLine();
} catch(IOException e) {
System.out.println("Erro de entrada");
}
System.out.println("Escreva uma letra para encontrar na frase: ");
try {
letra = cd.readLine();
} catch(IOException e) {
System.out.println("Erro de entrada");
}
int contador = 0;
for(int i = 0; i < frase.length(); i++) {
if(frase.charAt(i).equals(letra)) {
contador++;
}
}
if(contador == 0) {
System.out.println("Nao existe a letra na frase");
} else {
System.out.println("A letra aparece " + contador + " vezes");
}
}
}
However I'm getting the following error:
Exercicio1_string.java:37: error: char cannot be dereferenced if(frase.charAt(i).equals(letra)) {
That references this block of code:
int contador = 0;
for(int i = 0; i < frase.length(); i++) {
if(frase.charAt(i).equals(letra)) {
contador++;
}
}
I would like to know the reason for the error and if the charAt()
function and the equal()
function is being used correctly?