CIS-2271 Homework #4: Arrays

Due: Thursday, September 25, 2014

Read Chapter 6 in the text on arrays. You can skip the section on using arrays with methods since we haven't yet discussed methods.

Write a program that does the following things. As a convenience you can write a single program with a single main method that solves each of the parts below. Include in comments which part of your program is intended to solve which part of this assignment.

  1. Accept a line of text from the user and create an array of characters the same size as the line. Copy each character of the string into a corresponding array element. For example the character at position 0 in the string should go into the 0th array element. Recall that strings have a charAt method that allows you to get a particular character.

    You might be motivated to do something like this because, unlike strings, arrays in Java can be modified "in place" without making a copy every time. Thus if you need to extensively rework the text of a string it may be beneficial to put it into an array first. There are methods in the Java library that let you do this kind of thing precisely for this reason, but don't use them for this assignment. This is illustrated below.

  2. Modify the array you created in the previous example so that the charcters are put in reverse order. For example, suppose the array had three elements with 'x' in the first, 'y' in the second, and 'z' in the third. You want to reverse the contents so 'z' is in the first element, 'y' is in the second, and 'x' is in the third.

    One way to do this is to write a loop that processes half the array and exchanges array elements as it goes. For example it could exchange element number 0 with the last element, element number 1 with the second to last element, and so on. Here are a couple of hints to get you started:

  3. You can create a new string containing the characters of your modified array like this:

            String result = new String(myArray);
          

    After doing so, print the value of result to see if your modifications are correct. For example if the user enters "I like Java" the program should output "avaJ ekil I"


Last Revised: 2014-09-18
© Copyright 2014 by Peter C. Chapin <PChapin@vtc.vsc.edu>