Solution for in-class exercise (Feb. 18th). The program reads elements of a string array from the user's input.


public class ReadStringArray {

    public static void main (String [] args) throws IOException {
	// Create a buffered reader
	// need only one buffered reader for all your reading
	BufferedReader in = new BufferedReader(
			new InputStreamReader(;
	// string for storing a line of input
	String line;

	// Read the length
	// prompt the user:
        System.out.print("Please enter the length: ");
	// read a line of input:
	line = in.readLine();
	// extract the integer from the entered data:
	int length = Integer.parseInt(line);

	// create the array
	String [] a = new String[length];
	// read the elements
	for (int i = 0; i < length; ++i) {
	    System.out.print("Please enter an element: ");
	    line = in.readLine();
	    a[i] = line;

	// print out the elements to check:
	for (int i = 0; i < length; ++i) {
	    System.out.println("a[" + i +"] = " + a[i]);

This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.