Question 0-4

Complete the below class method so that it reads two strings from the user and displays ``yes'' if the second string includes only characters from the first, and ``no'' if it contains any characters that the first does not include.

For example, I should be able to execute your method and see the following. (Boldface indicates what the user types.)

brillig glib
yes
Or I might see the following. In this example, it prints ``no'' because broil includes the letter o, which does not occur in brillig.
brillig broil
no

public static void run() {



}

To accomplish this, you may find the following String instance methods useful. We discussed these in class.

int length()
Returns the number of characters in the target string.

char charAt(int i)
Returns the character at index i. For example, if str holds the string brillig, str.charAt(2) would return the character 'i'.

int indexOf(String s)
Returns the index where s occurs first within the string on which the method is called. If s occurs nowhere within the target string, the method returns -1. For example, if str holds the string brillig, str.indexOf("il") would return 2, since this is the index where il occurs first.

Solution

public static void run() {
    String first = IO.readString();
    String second = IO.readString();

    for(int i = 0; i < second.length(); i++) {
        if(first.indexOf("" + second.charAt(i)) == -1) {
            IO.println("no");
            return;
        }
    }
    IO.println("yes");
}
One of the subtleties of this answer that nobody correctly addressed was that the charAt() method returns a char, while the indexOf method requires a String. The solution is to append the character returned by charAt() to an empty string, which results in a string consisting only of that single letter that charAt() returns.

Back to Midterm 0