I’m having a hard time with this Prompt. I can solve this when the user input is “n Monday” but when the input is “Today is Monday, z”, “this is a sentence with many t’s, t” or “X, x” my code does not work. I am struggling to solve how to make both use cases work since the assignment is asking for that. So, it should be able to handle “n Monday” when character is first and string second, and also handle “Today is Monday, z” when string is first and character is second. I don’t know how to make both work at the same time.
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. The output should include the input character and use the plural form, n’s, if the number of times the characters appears is not exactly 1.
Ex: If the input is:
n Monday
the output is:
1 n
Ex: If the input is:
z Today is Monday
the output is:
0 z’s
Ex: If the input is:
n It’s a sunny day
the output is:
2 n’s
Case matters. n is different than N.
Ex: If the input is:
n Nobody
the output is:
0 n’s
The program must define and call the following method that takes the input string and character as parameters, and returns the number of times the input character appears in the input string.
public static int calcNumCharacters(String userString, char userChar)
This is the code I have so far:
` import java.util.Scanner;
public class LabProgram {
/* Define your method here */
public static String calcNumCharacters(char userChar, String userString) {
int count = 0;
// Count occurrences of userChar
for (int i = 0; i < userString.length(); ++i) {
if (userString.charAt(i) == userChar) {
++count;
}
}
// output
String output = count + " " + userChar;
if (count != 1) {
output += "'s";
}
return output;
}
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner (System.in);
//
char c = scnr.next().charAt(0);
String userInput = scnr.nextLine();
// condition: char and string
String result = calcNumCharacters(c, userInput);
System.out.println(result);
}
}`
i did try to make two methods
public static String calcNumCharacters(char userChar, String userString)
and I tried
public static String calcNumCharacters(String userString, char userChar)
and in my main method i did two method calls
String result = calcNumCharacters(c, userInput);
String result2 = calcNumCharacters(userInput, c);
thinking that if the input was Today is Monday, z that it would choose the second calcNumCharacter method. This is a lazy attempt at solving my problem and I can see it doesn’t workyour text
Isaac Garcia is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.