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

C++ for Engineers and Scientists
4th Edition
ISBN:9781133187844
Author:Bronson, Gary J.
Publisher:Bronson, Gary J.
Chapter3: Assignment, Formatting, And Interactive Input
Section: Chapter Questions
Problem 1PP: (General math) a. Write a C++ program to calculate and display the value of the slope of the line...
icon
Related questions
Question
100%

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

Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 3 steps with 2 images

Blurred answer
Knowledge Booster
Returning value from Function
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ for Engineers and Scientists
C++ for Engineers and Scientists
Computer Science
ISBN:
9781133187844
Author:
Bronson, Gary J.
Publisher:
Course Technology Ptr