My main objective is to make Java read a string and from it, express how many times this one character occurs. I am having issues formating this piece of code so that the output would be like this:
Entered word: papaya
Letter A: 3
Right now what I get is this:
Entered word: papaya
Letter A: 1
Letter A: 2
Letter A: 3
This is my code. It uses scanner to ask for input from the user.
int aCount = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string: ");
String string = scan.nextLine();
string = string.toLowerCase();
System.out.println("Entered word: " +string);
for (int i=0; i < string.length();i++)
{
if(string.charAt(i)== 'a')
{
aCount++;
if(aCount > 0)
System.out.println("Letter A: " + aCount);
}
Aucun commentaire:
Enregistrer un commentaire