Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Vernon Day   on Dec 01 In Java Category.

  
Question Answered By: Holly Brown   on Dec 01

/* RainfallDataReader.java April 19, 2003 */

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

/** Reads data  from a text  file into a 2 dimensional
* floating point array. This assumes the data is
* formatted as row  and columns with each line of
* text representing a row of data for one month
* and each column or day  of data is separated by
* a space or tab. Since some months do not have
* 31 days, these array  entries will be null and
* ignored.
* @author: Charles Bell
* @ version: April 19, 2003
*/
public class RainfallDataReader{

private boolean debug = false;
private float[][]rainfallData;
private String dataFileName = "RainfallData.txt";

/* Twelve month  in a year. */
private int rows = 12;
/* Max number  of days i a month */
private int columns = 31;

/** Constucts a RainfallDataReader object. */
public RainfallDataReader(){
rainfallData = readData();
}

/** Runs the RainfallDataReader application. */
public static void main(String[] args){
new RainfallDataReader();

}

/** Loads the data form the text file  into a data array
* with the preconfigured dimensions.
*/
public float[][] readData(){
float[][] fileData = new float[rows][columns];
try{
FileReader fr = new FileReader(dataFileName);
BufferedReader br = new BufferedReader(fr);
String nextLine = "";
for (int row = 0; row < rows; row++){
while ((nextLine = br.readLine()) != null){
if (debug) System.out.println(nextLine);
StringTokenizer tokenizer = new
StringTokenizer(nextLine, " ");
int numberOfDays = tokenizer.countTokens();
for (int column = 0; column < numberOfDays; column++){
String nextNumberString = tokenizer.nextToken();
if (debug) System.out.println(nextNumberString);
/* By calling a method which generates an exception
* message external to this loop, the whole loop
* will not crash if a bad data entry is found.
*/
fileData[row][column] = toFloat(nextNumberString);
}
}
}
}catch(FileNotFoundException fnfe){
System.err.println("Could not find file: " + dataFileName);
}catch(IOException ioe){
System.err.println("Problem occurred while attempting"
+ " to read data from file: " + dataFileName);
}
return fileData;
}

/** Converts a data entry into a floating point value and
* signaling errors as a -1 and an error message.
*/
private float toFloat(String s){
float f = -1;
try{
f = Float.parseFloat(s);
}catch(NumberFormatException nfe){
System.err.println("Problem occurred while converting "
+ s + " to a float value.");
}
return f;
}

}

Share: 

 

This Question has 3 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Array help needed please Or get search suggestion and latest updates.


Tagged: