1
I need to make a program that takes a sentence, then a letter, and returns 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");
}
}
}
But I’m getting the following error:
Exercicio1_string.java:37: error: char cannot be dereferenced if(frase.charAt(i).equals(letra)) {
Which refers to that code block:
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 whether the functions charAt()
and equal()
are being used correctly.