CS 140 - Lab 16 Array Basics

Objectives

  1. Learn the basics of Java arrays including declaring an array, putting data in an array, and retrieving data from an array.

Method

Part I - Array Basics

  1. In a Lab16 class declare an array of names suitable for holding 5 names.
  2. What does the statement System.out.println(names.length); do?
  3. Use five assignment statements to assign the names "Hermione", "Harry", "Ron", "Dumbledore", and "Minerva" to the names array.
  4. Use a for-loop to print the names array out in reverse order, one name per line.
  5. Add a scanner s to your lab so we can read data from the user.
  6. The Scanner method nextLine() reads a string from the keyboard. Use a for-loop to read five names from the keyboard and put them in the names array.
  7. Use a for-loop to print a numbered list of the names back out to the console. For example, the output might look like
         1) Fred
         2) George
         3) Hermione
         4) Harry
         5) Dumbledore
      
  8. What happens if you just hit the enter key five times?
  9. What does the following code segment print?
        String sentence = "How many characters are in this sentence?";
        System.out.println(sentence.length());
      
  10. Write a new for-loop that computes the average name length of a list of five names. For example the average length of a name for the list above is 6.6.

© Ed Harcourt