Read data from file, write result into a new file(java) - java

I need to read some txt file, get data from it, find out average numbers and then write them into another file. I've done pretty much everything , but can not write needed values in a new file.
public static double KronKesk(double a, double b, double c){
return (a/2+b+c/2)/2;
}
public static double KronKesk2(double[] b){
int jag = 0;
double sum = 0;
for (int i = 0; i < b.length; i++) {
jag++;
}
jag = jag - 1;
sum = ArraySum(b) - b[0] - b[b.length-1];
return (b[0]/2 + sum +b[b.length-1]/2)/jag;
}
public static double ArraySum(double[] a){
double sum = 0;
for (int i = 0; i < a.length; i++) {
sum = sum+a[i];
}
return sum;
}
public static void main(String[] args) {
try{
String filePath = "C:\\Users\\user\\Desktop\\TLU\\Semester 2\\ProgPohikursus\\temp";
BufferedReader br = new BufferedReader(new FileReader(filePath + ".txt"));
String rida;
List<Andmed> andmed = new ArrayList<>();
int ridaCount = 0;
while((rida = br.readLine()) != null){
String[] temp = rida.split(",");
Andmed andmed0 = new Andmed();
andmed0.setKuupaev(Double.valueOf(temp[0]));
andmed0.setTemp0(Double.valueOf(temp[1]));
andmed0.setTemp6(Double.valueOf(temp[2]));
andmed0.setTemp12(Double.valueOf(temp[3]));
andmed0.setTemp18(Double.valueOf(temp[4]));
andmed0.setTemp24(Double.valueOf(temp[5]));
andmed.add(andmed0);
ridaCount++;
}
System.out.println(andmed);
br.close();
File fout = new File(filePath + "_avgtemp" + ".txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
Andmed andmed0 = new Andmed();
for (int i = 0; i < ridaCount; i++) {
double[] andmed1 = {andmed0.getTemp0(), andmed0.getTemp6(), andmed0.getTemp12(), andmed0.getTemp18(), andmed0.getTemp24()};
double[] andmedFaili = {andmed0.getKuupaev(), KronKesk2(andmed1)};
bw.write(Arrays.toString(andmedFaili) + "\n");
}
bw.close();
} catch(Exception ex){
ex.printStackTrace();
}
}
}
and another file with getters and setters:
public class Andmed {
private double k;
private double t0;
private double t6;
private double t12;
private double t18;
private double t24;
/*protected static List<Double> allTemp = new ArrayList<Double>();
public double tempListi(double t0, double t6, double t12, double t18, double t24){
allTemp.add(t0);
allTemp.add(t6);
allTemp.add(t12);
allTemp.add(t18);
allTemp.add(t24);
return 0;
}*/
public void setKuupaev(double k){
this.k = k;
}
public void setTemp0(double t0){
this.t0 = t0;
}
public void setTemp6(double t6){
this.t6 = t6;
}
public void setTemp12(double t12){
this.t12 = t12;
}
public void setTemp18(double t18){
this.t18 = t18;
}
public void setTemp24(double t24){
this.t24 = t24;
}
public double getKuupaev(){
return k;
}
public double getTemp0(){
return t0;
}
public double getTemp6(){
return t6;
}
public double getTemp12(){
return t12;
}
public double getTemp18(){
return t18;
}
public double getTemp24(){
return t24;
}
}
What I have in a first file is:
12.01,3,4,5,6,7,8
13.01,4,5,5,4,3,6
...
what i need to get into a new file:
12.01, chronological average of 6 previous numbers
what do I get for now is:
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
Where is the mistake? :/
Thank You in advance!

In your for loop you are not using your list at all, but an empty andmed0 variable that you declared just before the loop.
Get rid of that variable and use the actual list :
// Andmed andmed0 = new Andmed(); // no need for that
for (int i = 0; i < ridaCount; i++) {
Andmed currentAndmed = andmed.get(i);
double[] andmed1 = {currentAndmed.getTemp0(), currentAndmed.getTemp6(), currentAndmed.getTemp12(), currentAndmed.getTemp18(), currentAndmed.getTemp24()};
double[] andmedFaili = {currentAndmed.getKuupaev(), KronKesk2(andmed1)};
bw.write(Arrays.toString(andmedFaili) + "\n");
}
Also note that you don't have to use a ridaCount variable to compute the size of the list, just call andmed.size() instead .
i.e :
for (int i = 0; i < andmed.size(); i++)
Finally as stated in the comments by #gilfernandes, you may simply use a foreach loop :
for(Andmed currentAndmed : andmed) {
double[] andmed1 = {currentAndmed.getTemp0(), currentAndmed.getTemp6(), currentAndmed.getTemp12(), currentAndmed.getTemp18(), currentAndmed.getTemp24()};
double[] andmedFaili = {currentAndmed.getKuupaev(), KronKesk2(andmed1)};
bw.write(Arrays.toString(andmedFaili) + "\n");
}

Related

Having trouble calling another class that reads a txt file into an array that is sorted in the program(band operand error)

so I have a program that takes a txt file and is read in and uses the class of another java file to set up the array. I am trying use selection sort to sort the values placed into the array but it gives me bad operand types for the line: (if array[j] < array[min]). The text file used is:"Country" "Total CO2 2005 (million tonnes)" "Road CO2 (million tonnes)" "Road CO2 per person (tonnes)" "Cars per 1000 people"
10
USA 5951.13 1530.3 5.16 777
UK 2573.4 119.68 1.99 470
Italy 476.08 116.86 2 592
Germany 841.78 150.21 1.82 550
Canada 553.02 123.42 3.82 562
France 414.03 128.13 2.04 477
Russia 1575.44 114.69 0.8 178
Japan 1254.47 224.24 1.76 447
China 5100.6 228.02 0.3 17
India 1147.46 91.06 0.1 8
The program with the class being called carbonDioxide.java:
public class CarbonDioxideData {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CarbonDioxideData() {
country = "blank_country";
totalCO2 = -1.0;
roadCO2 = -1.0;
CO2PerPerson = -1.0;
carsPerPerson = -1;
}
public String toString() {
String result = country;
result += " " + totalCO2;
result += " " + roadCO2;
result += " " + CO2PerPerson;
result += " " + carsPerPerson;
return result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
The program I am writing calling the two above, CarbonAnalysis.java:
import java.io.*;
import java.util.*;
public class CarbonAnalysis {
public static void main(String[]args){
//CarbonDioxideData c1 = new CarbonDioxideData();
//c1.setCountry("canada");
//System.out.println(c1);
Scanner userInput = new Scanner(System.in);
String fileName ="";
File inputFile = null;
Scanner fileReader = null;
while(fileReader==null){
try{
System.out.println("Enter input file name:");
fileName= userInput.next();
inputFile = new File(fileName);
fileReader = new Scanner(inputFile);
System.out.println("Successfully opening " + fileName);
}catch(IOException err){
System.out.println("Something went wrong");
System.out.println(err);
System.out.println("Please retry");
}
}
String testLine = fileReader.nextLine();
System.out.println(testLine);
int numberOfEntries = fileReader.nextInt();
System.out.println(numberOfEntries);
CarbonDioxideData[] array = new CarbonDioxideData[numberOfEntries];
for(int i =0;i<numberOfEntries;i++){
CarbonDioxideData c1 = new CarbonDioxideData();
String country = fileReader.next();
c1.setCountry(country);
double totalCO2 = fileReader.nextDouble();
c1.setTotalCO2(totalCO2);
double roadCO2 = fileReader.nextDouble();
c1.setRoadCO2(roadCO2);
double perPerson = fileReader.nextDouble();
c1.setCO2PerPerson(perPerson);
int cars = fileReader.nextInt();
c1.setCarsPerPerson(cars);
//System.out.println(c1);
array[i]=c1;
}
printArray(array);
emissionStats(array);
}
public static void printArray(CarbonDioxideData[] a){
for(int i=0; i<a.length;i++){
System.out.println(a[i]);
}
}
public static void emissionStats(CarbonDioxideData[] array){
for (int i = 0; i < array.length - 1; i++) {
// find index of smallest remaining value
int min = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[min]) {
min = j;
}
}
// swap smallest value its proper place, a[i]
swap(array, i, min);
}
}
public static void swap(CarbonDioxideData[] a, int i, int j) {
if (i != j) {
CarbonDioxideData temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
The error I am receiving when compiling:
CarbonAnalysis.java:68: error: bad operand types for binary operator '<'
if array[j] < array[min]
first type: CarbonDioxideData
Second type: CarbondDioxidedata
I am at a loss I have no idea how to get it to work. Any help appreciated
< , > binary operators can be used with primitive types.
public class CarbonDioxideData implements Comparable<CarbonDioxideData> {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
#Override
public int compareTo(CarbonDioxideData that) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == that) return EQUAL;
//Compare function according to your logic
if (this.totalCO2 == that.totalCO2) return EQUAL;
if (this.totalCO2 > that.totalCO2)
return AFTER;
else
return BEFORE;
}
}
Your comparison should be as
if (array[j].compareTo(array[min]) < 0) {
min = j;
}

Sorting arrays from a file and printing results

I have to read a file of data and store it into an array of integers, sort through the array and then report the highest total and the lowest total but for some reason when i run my code nothing appears, and it says that it is error free. this is the code that i have so far...
import java.io.*;
import java.util.Scanner;
public class CarbonAnalysis {
public static void main (String [] Args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
File f = new File("carbon_data.txt");
Scanner welcome = new Scanner(f);
File outputFile = new File("carbon_report.txt");
PrintStream output = new PrintStream(outputFile);
String firstLine = welcome.nextLine();
int secondLine = welcome.nextInt();
CarbonDioxideData[] Country = new CarbonDioxideData[secondLine];
for(int i = 0; i < secondLine; i++) {
Country[i] = new CarbonDioxideData();
Country[i].setCountry(welcome.next());
Country[i].setTotalCO2(welcome.nextDouble());
Country[i].setRoadCO2(welcome.nextDouble());
Country[i].setCO2PerPerson(welcome.nextDouble());
Country[i].setCarsPerPerson(welcome.nextInt());
}
int count = 0;
int count2 = 0;
CarbonDioxideData[] totalEmissions = new CarbonDioxideData[count];
CarbonDioxideData[] perPersonRoadEmissions = new CarbonDioxideData[count2];
reportDescription(output);
sortTotalEmissions(totalEmissions);
sortPerPersonRoadEmissions(perPersonRoadEmissions);
}
//prints the output of data analyzed
public static void reportDescription(PrintStream output) {
output.println("Country with the lowest total emissions: ");
output.println("Country with the highest total emissions: " );
output.println("Canada is ranked for lowest total emissions.");
output.println();
output.println("Country with the lower per-person road emissions: ");
output.println("Country with the highest per-person road emissions: ");
output.println("Canada is ranked for the lowest per-road emissions.");
}
//sorts the total Emissions from highest to lowest
public static void sortTotalEmissions(CarbonDioxideData[] totalEmissions){
for(int i = 0; i < totalEmissions.length; i++) {
double max = totalEmissions[i].getTotalCO2();
int maxPos = i;
for(int j = i; j < totalEmissions.length; j++) {
if(max < totalEmissions[j].getTotalCO2() ) {
max = totalEmissions[j].getTotalCO2();
maxPos = j;
}
}
CarbonDioxideData temp = totalEmissions[maxPos];
totalEmissions[maxPos] = totalEmissions[i];
totalEmissions[i] = temp;
}
}
//sorts the per person road Emissions from highest to lowest
public static void sortPerPersonRoadEmissions(CarbonDioxideData[] perPersonRoadEmissions){
for(int i = 0; i < perPersonRoadEmissions.length; i++) {
int max = perPersonRoadEmissions[i].getCarsPerPerson();
int maxPos = i;
for(int j = i; j < perPersonRoadEmissions.length; j++) {
if(max < perPersonRoadEmissions[j].getCarsPerPerson() ) {
max = perPersonRoadEmissions[j].getCarsPerPerson();
maxPos = j;
}
}
CarbonDioxideData temp = perPersonRoadEmissions[maxPos];
perPersonRoadEmissions[maxPos] = perPersonRoadEmissions[i];
perPersonRoadEmissions[i] = temp;
}
}
}
The code that was given to me to help:
public class CarbonDioxideData {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CarbonDioxideData() {
country = "blank_country";
totalCO2 = -1.0;
roadCO2 = -1.0;
CO2PerPerson = -1.0;
carsPerPerson = -1;
}
public String toString() {
String result = country;
result += " " + totalCO2;
result += " " + roadCO2;
result += " " + CO2PerPerson;
result += " " + carsPerPerson;
return result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
Your program always ouputs a constant String in the file since there is no variable in reportDescription.
Secondly to properly sort you array, CarbonDioxideData should implement Comparable. Then you can call
Arrays.sort like this :
Arrays.sort(perPersonRoadEmissions)
and then retrieve the highest/value :
perPersonRoadEmissions[0] / perPersonRoadEmissions[perPersonRoadEmissions.length-1]
To display the information you have to call output after sorting and change the signature to accept variable for highest and lowest value.
Arrays.sort(totalEmissions);
Arrays.sort(perPersonRoadEmissions)
reportDescription(output,totalEmissions[0],totalEmissions[totalEmissions.length-1],perPersonRoadEmissions[0],perPersonRoadEmissions[perPersonRoadEmissions.length-1]);
As an alternative you can also simply pass the arrays as parameters and retrieve min max in the body of reportDescription :
reportDescription(output,totalEmissions,perPersonRoadEmissions);
How to change the content of reportDescription and implementing compareTo is left to the OP.

java.lang.NullPointerException in two related java class

I implemented two java classes to solve the percolation problem but it throws the following exception
java.lang.NullPointerException
at PercolationStats.<init>(PercolationStats.java:24)
at PercolationStats.main(PercolationStats.java:54)
Program:
public class PercolationStats {
int t=0;
double[] sample_threshold;
Percolation B;
int N1;
public PercolationStats(int N, int T) {
t=T;
N1 = N;
int number_of_open=0;
for(int i=0;i<T;i++) {
B=new Percolation(N1);
while(!B.percolates()) {
double r1 = Math.random();
int open_i = (int)(r1*N1);
double r2 = Math.random();
int open_j = (int)(r2*N1);
B.open(open_i,open_j);
}
for(int k=0;k<N1;k++) {
for(int j=0;j<N1;j++) {
if(B.isOpen(k, j))
number_of_open++;
}
sample_threshold[i] = (number_of_open*1.0)/N1;
}
}
}
public double mean() {
double sum = 0.0;
for(int i=0;i<N1;i++) {
sum += sample_threshold[i];
}
return sum/t;
}
public double stddev() {
double sum = 0.0;
double u = mean();
for(int i=0;i<N1;i++) {
sum += (sample_threshold[i]-u)*(sample_threshold[i]-u);
}
return sum/(t-1);
}
public double confidenceLo() {
return mean()-((1.96*Math.sqrt(stddev()))/(Math.sqrt(t)));
}
public double confidenceHi() {
return mean()+((1.96*Math.sqrt(stddev()))/(Math.sqrt(t)));
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
PercolationStats C=new PercolationStats(N,T);
double mean=C.mean();
double stddev = C.stddev();
double confidenceLo = C.confidenceLo();
double confidenceHi = C.confidenceHi();
System.out.println("mean = "+mean);
System.out.println("stddev = "+stddev);
System.out.println("95% confidence interval = "+confidenceLo+", "+confidenceHi);
}
}
You never initialized double[] sample_threshold;. Hence it is null.
Java will indeed fill a double[] with 0.0 once it is initialized to a known size. You must initialize the array first:
public PercolationStats(int N, int T) {
t=T;
N1 = N;
sample_threshold[i] = new double[T]; // add this line
int number_of_open=0;
for(int i=0;i<T;i++) {
B=new Percolation(N1);
while(!B.percolates()) {
double r1 = Math.random();
int open_i = (int)(r1*N1);
double r2 = Math.random();
int open_j = (int)(r2*N1);
B.open(open_i,open_j);
}
for(int k=0;k<N1;k++) {
for(int j=0;j<N1;j++) {
if(B.isOpen(k, j))
number_of_open++;
}
sample_threshold[i] = (number_of_open*1.0)/N1;
}
}
}
here at 3rd line where you've written double[] sample_threshold;
instead just write double[] sample_threshold= new double[5000];
meaning just initalize the array. Then when you use it in for loop java will only consider the arrays for the times your for loop loops.

average method arrays hint

Can you give me a hint on what I'm doing wrong with my average in the average method? I'm trying to call the method in the read scores.I'm trying to get the average of the scores I have in my input.txt file.
import java.io.*;
import java.util.*;
public class FindGrade {
public static final int NUM_SCORE_TYPES = 5;
public static void main(String[] args) {
Scanner scan = null;
int[] quizArray = null;
int[] labArray = null;
int[] attendance = null;
int[] midterms = null;
int quizgrade =0;
int labgrade=0;
int attendance_1=0;
int midterms_1 =0;
String name;
try {
scan = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
// each iteration is for single exam type (ie: Quizzes is the 1st one)
for (int i = 0; i < NUM_SCORE_TYPES; i++) {
name = scan.next();
int numScores = scan.nextInt();
int maxGrade = scan.nextInt();
if (name.equals("Quizzes")) {
quizArray = new int[numScores];
readScores(quizArray, numScores, scan);
}
else if (name.equals("Labs")) {
labArray = new int[numScores];
readScores(labArray, numScores, scan);
}
else if (name.equals("Lab_attendance")) {
attendance = new int[numScores];
readScores(attendance, numScores, scan);
}
else if (name.equals("Midterms")) {
midterms = new int[numScores];
readScores(midterms, numScores, scan);
}
}
}
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
}
public static void average(double [] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}
In any case, you can't directly call it with the arrays that you are creating there. Because the arrays are of type int, but the average-method requires a double array. When you change this, you can call the method like this...
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
average(scoreArray, numScores); // <----- Call it here
}
public static void average(int[] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}

Client and Object Class outputting values

I have an object and client class created which prints coordinates in order of their distance from the origin. The client class asks the user how many dimensions they want the array to have (x,y or x,y,z) how many points they want generated, and a range from which each coordinate will run from (ex. -x to x, -y to y etc.). When I run the program it prints out the correct number of points, but there is always one extra element in the array (etc. when user enters dimension of array as '4', it always prints out one extra element -> [4, 5, 9, 6, 1]). Why is this happening?
Client Class
import java.io.*;
public class MA {
public MA() { }
public static void main(String args[]) throws IOException {
String myString = "arrayNumPoints.txt";
int numpoints = 0;
int dimension = 0;
double lengthscale = 0;
double [][] points = new double[numpoints][dimension + 1];
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
MB pointsB = new MB();
System.out.println("Enter number of points:");
String numpointsA = myInput.readLine();
numpoints = Integer.parseInt(numpointsA);
pointsB.setnumpoints(numpoints);
System.out.println("Enter the dimension:");
String dimensionA = myInput.readLine();
dimension = Integer.parseInt(dimensionA);
pointsB.setdim(dimension);
System.out.println("Enter length(range):");
String lengthscaleA = myInput.readLine();
lengthscale = Double.parseDouble(lengthscaleA);
pointsB.setlengthscale(lengthscale);
pointsB = new MB(numpoints, lengthscale, dimension, points);
pointsB.fillarray(pointsB.getarray(), pointsB.getlengthscale(), pointsB.getdim(), pointsB.getnumpoints());
pointsB.caldistance(pointsB.getarray(), pointsB.getnumpoints(), pointsB.getdim());
pointsB.sort(pointsB.getarray(), 0, pointsB.getnumpoints()-1, pointsB.getdim());
pointsB.writefile(pointsB.getarray(), pointsB.getnumpoints(), myString);
pointsB.readfile(myString);
}
}
Object Class
import java.io.*;
import java.util.Arrays;
public class MB {
//variables and arrays are declared
private double lengthscale;
private int numpoints;
private int dimension;
private double [][] points;
//constructor
public MB() { }
//constructor
public MB(double [][] points) {
numpoints = 0;
lengthscale = 0;
dimension = 0;
points = new double[numpoints][dimension + 1];
}
//constructor
public MB(int mynumpoints, double mylengthscale, int mydimension, double [][] mypoints) {
numpoints = mynumpoints;
lengthscale = mylengthscale;
dimension = mydimension;
points = new double[numpoints][dimension + 1];
}
//numpoints getter
public int getnumpoints()
{
return numpoints;
}
//numpoints setter
public void setnumpoints(int mynumpoints) {
numpoints = mynumpoints;
}
//lengthscale getter
public double getlengthscale() {
return lengthscale;
}
//lengthscale setter
public void setlengthscale(double mylengthscale) {
lengthscale = mylengthscale;
}
//dimension getter
public int getdim() {
return dimension;
}
//dimension setter
public void setdim(int mydimension) {
dimension = mydimension;
}
//array getter
public double[][] getarray() {
return points;
}
//array setter
public void setarray(double [][]mypoints, int numpoints, int dimension) {
points[numpoints][dimension] = mypoints[numpoints][dimension];
}
//fill array method
public void fillarray(double [][]mypoints, double mylengthscale, int mydimension, int mynumpoints) throws IOException {
for(int x = 0; x < mynumpoints; x++)
{
for(int y = 0; y < mydimension; y++) {
//fills array with random points within the specified range
mypoints[x][y] = (dimension * Math.random() - 1) * mylengthscale;
}//end for
}//end for
}
//writefile method
public void writefile(double [][]mypoints, int mynumpoints, String myString) throws IOException {
//writes to myString
PrintWriter fileOut = new PrintWriter(new FileWriter(myString));
//for loop runs for length of mylengthscale
for(int m = 0; m < mynumpoints; m++) {
//prints points to file
fileOut.println(Arrays.toString(mypoints[m]));
}
//close file
fileOut.close();
//end for
}
//readfile metod
public void readfile(String myString) throws IOException
{
String filePath = myString;
//reads data from mString
BufferedReader in = new BufferedReader(new FileReader(new File(myString)));
String line = null;
while(( (line = in.readLine()) != null))
System.out.println(line);
in.close();
}
//caldistance method
public void caldistance(double [][]mypoints, int mynumpoints, int mydimension) {
//for loop; calculates distance for specified number of points
for(int i = 0; i < mynumpoints; i++) {
for(int k = 0; k < mydimension; k++) {
mypoints[i][mydimension] = mypoints[i][k] * mypoints[i][k];
}//end for loop
mypoints[i][mydimension] = Math.sqrt(mypoints[i][mydimension]);
}//end for loop
}
//sort method
public double[][] sort(double[][] mynewpoints, int down, int top, int mydimension) {
System.arraycopy(mynewpoints, 0, mynewpoints, 0, mynewpoints.length);
//variables are declared
int d = down;
int u = top;
//determines pivot point
double [] pivot = mynewpoints[(down + top)/2];
//sorts the values of the array, comparing it to the pivot
do {
while (mynewpoints[d][mydimension] < pivot[mydimension]) {
d++;
}
while (mynewpoints[u][mydimension] > pivot[mydimension]) {
u--;
}
if (d <= u) {
double[] temporary = new double[mynewpoints[d].length];
//compres values in array and switches them
for (int y = 0; y < mynewpoints[d].length; y++) {
temporary[y] = mynewpoints[d][y];
mynewpoints[d][y] = mynewpoints[u][y];
mynewpoints[u][y] = temporary[y];
}
d++;
u--;
}
} while (d <= u);
if (down < u) {
mynewpoints = sort(mynewpoints, mydimension, down, u);
}
if (d < top) {
mynewpoints = sort(mynewpoints, mydimension, d, top);
}
return mynewpoints;
}
}
You should be more specific (show us the code fragments, which you use and which go wrong).
However do you realize, that in your MB constructor :
//constructor
public MB(double [][] points) {
numpoints = 0;
lengthscale = 0;
dimension = 0;
points = new double[numpoints][dimension + 1];
}
The last line is not doing anything? You have to write it like this :
this.points = new double[numpoints][dimension + 1];
Because you have two variables points, one is class variable, second is passed as parameter. If this happens, without using this the non-class variable is chosen.
Probably because you're adding 1 to the dimension given by the user:
points = new double[numpoints][dimension + 1];
This results in the array having one more column than value of dimension.

Categories

Resources