Skip to content

Instantly share code, notes, and snippets.

@tatey tatey/Lab5.java
Created Aug 27, 2008

Embed
What would you like to do?
Solution to Lab 5 for 1005ICT
/**
* @author Tate Johnson
* @version 2008-08-20
*/
public class Lab5 {
// Instance variable
private double[] data;
/**
* Constructor
*
* @param length Length of array
* @param val Value to be populated at each index
*/
public Lab5(int length, double val) {
data = new double[length];
for (int i = 0; i < data.length; i++) {
data[i] = val;
}
}
/**
* Constructor
*
* @param data A double array
*/
public Lab5(double[] data) {
this.data = data;
}
/**
* @return Object's double array
*/
public double[] getArray() {
return data;
}
/**
* @return Length of object's double array
*/
public int getLength() {
return data.length;
}
/**
* @param pos Index position of double array
* @param val Value to be replaced at <code>pos</code>
*/
public void setVal(int pos, double val) {
// Ensure that pos is a legal position within array
if (pos < data.length && pos >= 0) {
data[pos] = val;
}
}
public void print() {
String toPrint = new String();
for (int i = 0; i < data.length; i++) {
// Not last position in array
if (i != data.length - 1) {
toPrint += data[i] + ", ";
}
else {
toPrint += data[i];
}
}
System.out.println("{" + toPrint + "}");
}
/**
* @param val Double value to be compared against the value's in object
* @return Number of values in object that's greater than <code>val</code>
*/
public int greaterCnt(double val) {
int count = 0;
for (double d : data) {
if (d > val) {
count++;
}
}
return count;
}
/**
* @return Index position of greatest value in object's double array
*/
public int max() {
int pos = 0;
double max = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
pos = i;
}
}
return pos;
}
/**
* @return copyData An element for element copy of object's double array
*/
public double[] copy() {
double[] copyData = new double[data.length];
for (int i = 0; i < copyData.length; i++) {
copyData[i] = data[i];
}
return copyData;
}
public void setRandom() {
for (int i = 0; i < data.length; i++) {
data[i] = Math.random();
}
}
/**
* @return Integer array copy of object's double array
*/
public int[] toInt() {
int[] toIntData = new int[data.length];
for (int i = 0; i < toIntData.length; i++) {
// Instantiate new double object and assign returned int value
// to position in array
toIntData[i] = new Double(data[i]).intValue();
}
return toIntData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.