/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package randomtestfile; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.Scanner; /** * * @author jcmtiernan */ public class RandomTestFile { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { final int ROWMAX = 10; final int COLMAX = 30; int[][] array2DTest = new int[ROWMAX][COLMAX]; // this code generates a file of random numbers that can then be used // to repeat tests for other programs File fileIn; Scanner input; fileIn = fileFill(300); try { input = new Scanner(fileIn); } catch (FileNotFoundException fnf) { System.out.println("No file randomOut.txt found"); input = new Scanner(System.in); } for( int r = 0; r < ROWMAX; r++) for(int c = 0; c < COLMAX; c++) { if (input.hasNextInt()) { array2DTest[r][c] = input.nextInt(); } } // Verifying data from file try { input = new Scanner(fileIn); } catch (FileNotFoundException fnf) { System.out.println("No file randomOut.txt found"); input = new Scanner(System.in); } int count = 0; System.out.println("File randomOut.txt contains:"); while (input.hasNextInt()) { System.out.printf("%8d",input.nextInt()); if (count++ % 10 == 9) { System.out.println(); } } System.out.println(); System.out.println(); System.out.println("array2DTest contains:"); for( int r = 0; r < ROWMAX; r++) { System.out.println("Elements on row "+r+" are: "); for(int c = 0; c < COLMAX; c++) { System.out.printf("%8d",array2DTest[r][c]); if (c % 10 == 9) { System.out.println(); } } System.out.println(); } } public static File fileFill(int count) throws IOException { File file = new File("randomOut.txt"); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); Scanner fileIn; // data will be put into the file in rows of 10 elements with a // total of ROWMAX * COLMAX values Random rand = new Random(); int randomNumber; for(int k = 0; k < count; k++) { randomNumber = rand.nextInt(10000); // 0-9999. bw.write(String.format("%8d", randomNumber)); if ((k % 10) == 9) { bw.newLine(); } } bw.close();// be sure to close BufferedWriter return file; } }