Solution for in-class exercise (Feb. 18th). The program reads
elements of an array from the user's input.
import java.io.*;
public class ReadIntArray {
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(System.in));
// 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
int [] a = new int[length];
// read the elements
for (int i = 0; i < length; ++i) {
System.out.print("Please enter an element: ");
line = in.readLine();
a[i] = Integer.parseInt(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.