home >4.16: Lab4c: LetterCount Loops do just what they sound like they should-th
ID: 3594107 • Letter: H
Question
home >4.16: Lab4c: LetterCount Loops do just what they sound like they should-they perform a statement again and again untl a condition is For this lab you will be practicing using loops, specifically a for loop The for loop takes the form of for (/*variable initialization-7;/*stop condition * /tincrement*/) { //statements to be done multiple times Task Write a program that accepts a string and a character to search for in the string The progam should count and dsplaythe number of Sample output for input of 'Once upon a time, when ice covered the earth' and 'e The letter e' appears 8 times in the string "Once upon a time, when ice covered the earth." javaExplanation / Answer
import java.util.Scanner;
public class LetterCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String line = sc.nextLine();
System.out.print("Enter a letter to search: ");
char c = sc.next().charAt(0);
sc.close();
int count = 0;
// looping over characters of input string
for(int i=0; i<line.length(); i++) {
// increasing the count if it matches with c
if(c == line.charAt(i))
count++;
}
System.out.println("The letter "+c+" appears "+count+" times in the string: ""+line+""");
}
}
/*
Sample run:
Enter a string: this is my line
Enter a letter to search: i
The letter i appears 3 times in the string: "this is my line"
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.