Exercise 8.4 Write a method that finds the number of occurrences of a specified
ID: 3620941 • Letter: E
Question
Exercise 8.4
Write a method that finds the number of occurrences of a specified character in the string using the following header: public static int count(String str, char a).
For example, count("Welcome", 'e') returns 2.
What I'm attempting to do is have the user input a word and also input the letter to check how many times that specific letter occurres. Here is the code below. The bold is the location of the known error that I have. My question is what would I need to do to correct it so that it works properly.
import java.util.*;
public class Occurrence
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = input.nextLine();
System.out.print("Enter a letter: ");
char a = input.nextChar();
int letterCheck = Occurrence.count(str, a);
System.out.println("The word was: " + str);
System.out.println("The letter " + a + " was found this many times: " + letterCheck);
}
public static int count(String str, char a)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == a)
{
count++;
}
}
return count;
}
}
Explanation / Answer
please rate - thanks
import java.util.*;
public class Occurrence
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = input.nextLine();
System.out.print("Enter a letter: ");
char a = input.nextLine().charAt(0);
int letterCheck = Occurrence.count(str, a);
System.out.println("The word was: " + str);
System.out.println("The letter " + a + " was found this many times: " + letterCheck);
}
public static int count(String str, char a)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == a)
{
count++;
}
}
return count;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.