-
Notifications
You must be signed in to change notification settings - Fork 0
/
LetterCounter.java
42 lines (34 loc) · 1.26 KB
/
LetterCounter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Write a program that asks the user to enter
* a string and a character. The program should
* count and display the number of times that
* the specified character appears in the string.
*/
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Ask the user to enter a string
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Ask the user to enter a character
System.out.print("Enter a character to count: ");
char character = scanner.next().charAt(0);
int count = 0;
// Loop through the string to count occurrences of the character
for (int i = 0; i < inputString.length(); i++) {
if (inputString.charAt(i) == character) {
count++;
}
}
// Display the result
System.out.println("The character '" + character + "' appears " + count + " times in the string.");
scanner.close();
}
}
/**
* Explanation:
The program asks the user to input a string and a character.
It loops through the string and counts how many times the
specified character appears. The result is displayed to the user.
*/