In: Computer Science
Java program
Create a constructor for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations
private
double
timeStep;
// time between each data point
int
numberOfPoints;
// number of data samples in array
double [] acceleration = new double [1000];
// acceleration
data
double [] velocity = new double
[1000]; // calculated
velocity data
double [] displacement = new double
[1000]; // calculated
disp data
The constructor will have a single String parameter that is the name of the file with the data. That file has the timestep on the first line, followed by the data that should be put into the acceleration array, 1 data sample per line. The number of data samples is not known or in the file, but is less than 1000.
The constructor should open the file, put the value into timestep, and fill acceleration with the data in the file. At the end of the constructor, numberOfPoints should have the number of data points entered into acceleration. Close the file at the end of the constructor. Do not change either velocity or displacement.
In the constructor, be sure to catch an IOException error if the name of the file to be opened does not exist
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Signal {
private double timeStep;
private int numberOfPoints;
private double [] acceleration = new double [1000];
private double [] velocity = new double [1000];
private double [] displacement = new double [1000];
public Signal(String filename)
{
Scanner fileReader;
try
{
fileReader = new Scanner(new File(filename));
timeStep = Double.parseDouble(fileReader.nextLine().trim());
numberOfPoints = 0;
while(fileReader.hasNextLine())
{
acceleration[numberOfPoints++] =
Double.parseDouble(fileReader.nextLine().trim());
}
fileReader.close();
}catch(FileNotFoundException fnfe){
System.out.println(filename + " could not be found!
Exiting..");
System.exit(0);
}
}
public void displayData()
{
if(numberOfPoints == 0)
{
System.out.println("No acceleration data has been
recorded!\n");
return;
}
System.out.println("Timestep recorded: " + String.format("%.3f\n",
timeStep));
System.out.print("There are total " + numberOfPoints + "
acceleration data read from file.\n"
+ "Acceleration data: ");
for(int i = 0; i < numberOfPoints; i++)
System.out.print(String.format("%.3f", acceleration[i]) + "
");
System.out.println();
}
public static void main(String[] args) {
new Signal("signal.txt").displayData();
}
}
******************************************************* SCREENSHOT *********************************************************
INPUT FILE (signal.txt) - This file needs to be created before running the code and this file should be created within the same project directory where the above Signal.java file will be residing.
CONSOLE OUTPUT :