Reading and Writing to a File [Arrays]

Hi, this sample code is an implementation of two types of arrays, the one-dimensional and the two-dimensional. It reads and write numbers from and to a text file, passing arrays to static methods,  generating random numbers and uses control structures.

//Start of File J2.java

import java.io.*;
import java.util.*;

public class J2 {
public static void main(String[] args) throws IOException {
int row, col;
char charArray[] = {‘q’, ‘$’, ‘%’, ‘F’, ‘#’, ‘Z’, ‘y’, ‘Q’};

Random rNumbers = new Random();
double twoDimDiffCols[][] = new double[3][];
twoDimDiffCols[0] = new double[5];
twoDimDiffCols[1] = new double[3];
twoDimDiffCols[2] = new double[9];

double twoDimArray[][] = new double[3][5];

// display all values
for (char element : charArray)
System.out.print(element + ” “);
System.out.println();

// display the last 4 elements in reverse order
dispRevArray(charArray, charArray.length – 1, 3);

// initialize twoDimDiffCols with random numbers.
for (row = 0; row < twoDimDiffCols.length; row++)
for (col = 0; col < twoDimDiffCols[row].length; col++)
twoDimDiffCols[row][col] = 100 * rNumbers.nextDouble();

// display all values of twoDimDiffCols
dispTwoDimArray(twoDimDiffCols);

// Read numbers from a text file
Scanner inFile = new Scanner (new FileReader(“/home/icst214.ztn1/data.txt”));
for (row = 0; row < twoDimArray.length; row++)
for (col = 0; col < twoDimArray[row].length; col++)
twoDimArray[row][col] = inFile.nextDouble();
inFile.close();

// display
dispTwoDimArray(twoDimArray);

// write to a new file
writeFile(twoDimArray, “/home/icst214.ztn1/outData.txt”);
}

static void dispRevArray(char Array[], int start, int end) {
int i = start;
while (i >= end ) {
System.out.print(Array[i] + ” “);
i–;
}
System.out.println();
}

static void dispTwoDimArray(double Array[][]) {
for (double rows[] : Array) {
for (double cols: rows)
System.out.printf(“%.2f “, cols);
System.out.printf(“\n”);
}
System.out.printf(“\n”);
}

static void writeFile(double Array[][], String fileName) throws IOException {
FileWriter outFile = new FileWriter(fileName);
for (double rows[] : Array) {
for (double cols: rows)
outFile.write(cols + ” “);
outFile.write(“\n”);
}
outFile.close();

}
}

// EOF: J2.java

Leave a Comment