Skip to main content
Engineering LibreTexts

17.11: Exercises

  • Page ID
    19640
  • The code for this chapter is in the ch09 directory of ThinkJavaCode. See [Section 0.4] for instructions on how to download the repository. Before you start the exercises, we recommend that you compile and run the examples.

    Exercise \(\PageIndex{1}\)

    The point of this exercise is to explore Java types and fill in some of the details that aren’t covered in the chapter.

    1. Create a new program named Test.java and write a main method that contains expressions that combine various types using the + operator. For example, what happens when you “add” a String and a char? Does it perform character addition or string concatenation? What is the type of the result? (How can you determine the type of the result?)
    2. Make a bigger copy of the following table and fill it in. At the intersection of each pair of types, you should indicate whether it is legal to use the + operator with these types, what operation is performed (addition or concatenation), and what the type of the result is.
      boolean char int double String
      boolean
      char
      int
      double
      String
    3. Think about some of the choices the designers of Java made when they filled in this table. How many of the entries seem unavoidable, as if there was no other choice? How many seem like arbitrary choices from several equally reasonable possibilities? Which entries seem most problematic?
    4. Here’s a puzzler: normally, the statement x++ is exactly equivalent to x = x + 1. But if x is a char, it’s not exactly the same! In that case, x++ is legal, but x = x + 1 causes an error. Try it out and see what the error message is, then see if you can figure out what is going on.
    5. What happens when you add "" (the empty string) to the other types, for example, "" + 5?
    6. For each data type, what types of values can you assign to it? For example, you can assign an int to a double but not vice versa.

    Exercise \(\PageIndex{2}\)

    Write a method called letterHist that takes a string as a parameter and returns a histogram of the letters in the string. The zeroth element of the histogram should contain the number of a’s in the string (upper- and lowercase); the 25th element should contain the number of z’s. Your solution should only traverse the string once.

    Exercise \(\PageIndex{3}\)

    The purpose of this exercise is to review encapsulation and generalization (see Section 7.3). The following code fragment traverses a string and checks whether it has the same number of open and close parentheses:

    String s = "((3 + 7) * 2)";
    int count = 0;
    
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '(') {
            count++;
        } else if (c == ')') {
            count--;
        }
    }
    
    System.out.println(count);
    
    1. Encapsulate this fragment in a method that takes a string argument and returns the final value of count.
    2. Now that you have generalized the code so that it works on any string, what could you do to generalize it more?
    3. Test your method with multiple strings, including some that are balanced and some that are not.

    Exercise \(\PageIndex{4}\)

    Create a program called Recurse.java and type in the following methods:

    /**
     * Returns the first character of the given String.
     */
    public static char first(String s) {
        return s.charAt(0);
    }
    
    /**
     * Returns all but the first letter of the given String.
     */
    public static String rest(String s) {
        return s.substring(1);
    }
    
    /**
     * Returns all but the first and last letter of the String.
     */
    public static String middle(String s) {
        return s.substring(1, s.length() - 1);
    }
    
    /**
     * Returns the length of the given String.
     */
    public static int length(String s) {
        return s.length();
    }
    
    1. Write some code in main that tests each of these methods. Make sure they work, and you understand what they do.
    2. Using these methods, and without using any other String methods, write a method called printString that takes a string as a parameter and that displays the letters of the string, one on each line. It should be a void method.
    3. Again using only these methods, write a method called printBackward that does the same thing as printString but that displays the string backward (again, one character per line).
    4. Now write a method called reverseString that takes a string as a parameter and that returns a new string as a return value. The new string should contain the same letters as the parameter, but in reverse order.
      String backwards = reverseString("coffee");
      System.out.println(backwards);
      
      The output of this example code should be:
      eeffoc
    5. A palindrome is a word that reads the same both forward and backward, like “otto” and “palindromeemordnilap”. Here’s one way to test whether a string is a palindrome:
      A single letter is a palindrome, a two-letter word is a palindrome if the letters are the same, and any other word is a palindrome if the first letter is the same as the last and the middle is a palindrome.
      Write a recursive method named isPalindrome that takes a String and returns a boolean indicating whether the word is a palindrome.

    Exercise \(\PageIndex{5}\)

    A word is said to be “abecedarian” if the letters in the word appear in alphabetical order. For example, the following are all six-letter English abecedarian words:

    abdest, acknow, acorsy, adempt, adipsy, agnosy, befist, behint, beknow, bijoux, biopsy, cestuy, chintz, deflux, dehors, dehort, deinos, diluvy, dimpsy

    Write a method called isAbecedarian that takes a String and returns a boolean indicating whether the word is abecedarian. Your method can be iterative or recursive.

    Exercise \(\PageIndex{6}\)

    A word is said to be a “doubloon” if every letter that appears in the word appears exactly twice. Here are some example doubloons found in the dictionary:

    Abba, Anna, appall, appearer, appeases, arraigning, beriberi, bilabial, boob, Caucasus, coco, Dada, deed, Emmett, Hannah, horseshoer, intestines, Isis, mama, Mimi, murmur, noon, Otto, papa, peep, reappear, redder, sees, Shanghaiings, Toto

    Write a method called isDoubloon that takes a string and checks whether it is a doubloon. To ignore case, invoke the toLowerCase method before checking.

    Exercise \(\PageIndex{7}\)

    Two words are anagrams if they contain the same letters and the same number of each letter. For example, “stop” is an anagram of “pots” and “allen downey” is an anagram of “well annoyed”.

    Write a method that takes two strings and checks whether they are anagrams of each other.

    Exercise \(\PageIndex{8}\)

    In Scrabble1 each player has a set of tiles with letters on them. The object of the game is to use those letters to spell words. The scoring system is complex, but longer words are usually worth more than shorter words.

    Imagine you are given your set of tiles as a string, like "quijibo", and you are given another string to test, like "jib".

    Write a method called canSpell that takes two strings and checks whether the set of tiles can spell the word. You might have more than one tile with the same letter, but you can only use each tile once.


    Footnotes

    1. Scrabble is a registered trademark owned in the USA and Canada by Hasbro Inc., and in the rest of the world by J. W. Spear & Sons Limited of Maidenhead, Berkshire, England, a subsidiary of Mattel Inc.