Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // My String Method Problem,
- // Renee Waggoner
- // June 24, 2019
- // Special Requirements: None
- package string_methods;
- import java.util.Scanner;
- public class MyStringMethods {
- private String myStr = "";
- public void readString() {
- // Prompt the user and read in a String and then store
- Scanner keyboard = new Scanner(System.in);
- System.out.println("Enter in the desired String: ");
- myStr = keyboard.nextLine();
- keyboard.close();
- }
- public void setString(String s) {
- myStr = s;
- }
- // use indexOf and return the number of occurrences of the string "s"
- public int countOccurrences(String s) {
- int count = 0;
- int pos = myStr.indexOf(s, 0);
- while (pos != -1 && pos<myStr.length()) {
- pos = myStr.indexOf(s, pos+1);
- count++;
- }
- return count;
- }
- // use indexOf and return the number of occurrences of the character "c" in "myStr"
- public int countOccurrences(char c) {
- int count = 0;
- int pos = myStr.indexOf(c, 0);
- while (pos != -1) {
- pos = myStr.indexOf(c, pos+1);
- count++;
- }
- return count;
- }
- public int countLowerCaseLetters() {
- int lowerCaseLetters = 0;
- for (int i = 0; i < myStr.length(); i++)
- if (Character.isLowerCase(myStr.charAt(i))) {
- lowerCaseLetters++;
- }
- return lowerCaseLetters;
- }
- int countUpperCaseLetters() {
- int upperCaseLetters = 0;
- for (int i = 0; i < myStr.length(); i++)
- if (Character.isUpperCase(myStr.charAt(i))) {
- upperCaseLetters++;
- }
- return upperCaseLetters;
- }
- public void printCounts(String s, char c) {
- System.out.println("***************************************");
- System.out.println("Analyzing: myStr=" + myStr);
- System.out.println("Number of Upper case letters=" + countUpperCaseLetters());
- System.out.println("Number of Lower case letters=" + countLowerCaseLetters());
- System.out.println("Number of " + s + " is " + countOccurrences(s));
- System.out.println("Number of " + c + " is " + countOccurrences(c));
- }
- public static void main(String[] args) {
- MyStringMethods msm = new MyStringMethods();
- msm.readString();
- msm.printCounts("big", 'a');
- msm.setString("Parked in a van down by the river bank .... The vanevan vanished near a lot of other vans");
- msm.printCounts("van", 'a');
- MyStringMethods msm2 = new MyStringMethods();
- msm2.setString("the elephant in the room wouldn't budge");
- msm2.printCounts("the", 'i');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment