LAB: Count characters - methods Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in t
Problem:
9.17 LAB: Count characters - methods
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string.
Ex: If the input is:
n Monday
the output is:
1
Ex: If the input is:
z Today is Monday
the output is:
0
Ex: If the input is:
n It's a sunny day
the output is:
2
Case matters. n is different than N.
Ex: If the input is:
n Nobody
the output is:
0
Your program must define and call the following method that returns the number of times the input character appears in the input string.
public static int countCharacters(char userChar, String userString)
Java code:
import java.util.Scanner;
public class LabProgram {
/* Define your method here */public static int countCharacters(char userChar, String userString) {
int counter=0;
for (int i=0; userString.length; i++) {
if (userString.charAt(i)==userChar) {
counter++;
}
}
return counter;
}
}
public static void main(String[] args) {
/* Type your code here. */ Scanner scnr = new Scanner(System.in);
char userChar=scnr.next().charAt(0);
String userString=scnr.nextLine();
System.out.print(countCharacters);
}
}
My errors:
Failed to compile
LabProgram.java:18: error: class, interface, or enum expected
public static void main(String[] args) {
^
LabProgram.java:20: error: class, interface, or enum expected
char userChar=scnr.next().charAt(0);
^
LabProgram.java:21: error: class, interface, or enum expected
String userString=scnr.nextLine();
^
LabProgram.java:23: error: class, interface, or enum expected
System.out.print(countCharacters);
^
LabProgram.java:24: error: class, interface, or enum expected
}
^
5 errors
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 2 images