I have a test coming up in a java programming class. I need to know how to write
ID: 3634862 • Letter: I
Question
I have a test coming up in a java programming class. I need to know how to write this program, and what it looks like. It's for an intro class, so it should look rather simple, nothing too advanced. Here is what the book says:Write a method that finds the occurrences of a specified character in the string using the following heading:
public static int count(String str, char a)
for example, count("Welcome". "e") returns 2.Write a test program that prompts the user to enter a string followed by a character and displays the number of occurrences of the character in the string.
Explanation / Answer
public static int count(String str, char a)
{
// local variable for count
int count = 0;
// loop through characters in string
for(char c : str.toCharArray())
// check if character matches, if so, update count
if(c == a)
count++;
// output
return count;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.