Answer Key for Practice Quiz 3

  1. Write an expression that evaluates to true if and only if the integers i and j are greater than 10.
        i > 10 && j > 10
    
  2. Write an expression that evaluates to true if and only if i is positive or less than -10.
        i > 0 || i < -10
    
  3. Given an integer variable, hour, that has a value in the range of 0 - 23, declare a new String variable called suffix and initialize it to "AM" or "PM", depending on the value of hour. (0 - 11 should be "AM"; 12 - 23 should be "PM".)
        if ( hour < 12 )
        {
            suffix = "AM";
        }
        else
        {
            suffix = "PM";
        }
    
  4. Write a for loop that prints "Hooray!" 10 times, each time on a separate line.
        for ( int i = 0; i < 10; i++ )
        {
            System.out.println("Hooray!");
        }
    
  5. Declare a variable of type WordReader and initialize it to a new WordReader object. The WordReader constructor takes one parameter, a file name of type String. You can pass whatever string you like to the constructor as the filename.
        WordReader reader = new WordReader("SherlockHolmes.txt");
    
  6. Using the WordReader variable you declared and initialized above, use the nextLine() method to read in a line and print it. The nextLine() method does not take any parameters; it returns a String.
        System.out.println(reader.nextLine());
    
        // OR, String theLine = reader.nextLine();
        //     System.out.println(theLine);
    

Answer Key for Practice Quiz on Constructing and Looping through an ArrayList

  1. Declare a variable named words that is an ArrayList of String values, and initialize it to be an empty list.
        ArrayList<String> words = new ArrayList<String>();
    
  2. Add three strings to the ArrayList you created above: “Sherlock”, “Holmes”, and "Watson".
        words.add("Sherlock");
        words.add("Holmes");
        words.add("Watson");
    
  3. Write a for loop that prints the length of each string in the ArrayList you created above.
        for ( String oneWord : words )
        {
            int len = oneWord.length();
            System.out.println(len);    // OR, System.out.println(oneWord.length());
        }