Question 2-3

Write a program that reads a name from the user and displays the number of lower-case r's occurring in the name.

Name? Carl Bryan Burch
You have 3 r's.
You'll want to use the instance methods length() and charAt() defined in the String class. Your program's interface should be identical to the above transcript.
import csbsju.cs160.*;

public class PrintHello {
    public static void main(String[] args) {


    }
}

Solution

public class PrintHello {
    public static void main(String[] args) {
        IO.print("Name? ");
        String name = IO.readLine();
        int count = 0;
        for(int i = 0; i < name.length(); i++) {
            if(name.charAt(i) == 'r') ++count;
        }
        IO.println("You have " + count + " r's.");
    }
}

Back to Review for Quiz 2