For this question, you will be required to refactor a program in Java. Synopsis:
ID: 665155 • Letter: F
Question
For this question, you will be required to refactor a program in Java.
Synopsis:
Consider the code below.
public class E3RefactorA {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter a string: ");
String s = input.nextLine();
System.out.print("Enter a character: ");
char ch = input.nextLine().charAt(0);
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ch) {
count++;
}
}
System.out.println(count);
}
}
We want to be able to reuse the code that counts and returns the count of a specific char in a given string. Rewrite the program to include a call to a method countthat returns a count of chars in a given string. The method header to be used is
public static int count(String str, char ch)
Explanation / Answer
import java.util.*;
public class Count_Letter
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Enter a string: ");
String str = input.nextLine();
System.out.println("Enter a character: ");
char ch = input.nextChar;
int letterCheck = Count_Letter(str, ch);
System.out.println("The character " + ch + "appeared" + letterCheck + "times in" + str);
}
public static int Count(String str, char ch)
{
int Count_Letter = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ch)
{
Count++;
}
}
return Count;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.