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.
Related
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");
}
i need to do a bubble sort with 2 different set of datas. currently i have entered the bubble sort method twice so it can run with both set of data. is there a way to use a call method to the bubble sort.
int intJ1R1 = Integer.parseInt(txtJ1R1.getText());
int intJ2R1 = Integer.parseInt(txtJ2R1.getText());
int intJ3R1 = Integer.parseInt(txtJ3R1.getText());
int intJ4R1 = Integer.parseInt(txtJ4R1.getText());
int intJ5R1 = Integer.parseInt(txtJ5R1.getText());
int intJ6R1 = Integer.parseInt(txtJ6R1.getText());
double[] r1Array = {intJ1R1, intJ2R1, intJ3R1, intJ4R1, intJ5R1, intJ6R1};
double temp;
for (int i=0; i<r1Array.length; i++)
{
for (int j = 1; j <(r1Array.length-i); j++)
{
if (r1Array[j-1]>=r1Array[j])
{
temp=r1Array[j-1];
r1Array[j-1] = r1Array[j];
r1Array[j] = temp;
}
}
}
double totalR1 = (r1Array[1] + r1Array[2] + r1Array[3] + r1Array[4])/4;
String stringTotalR1 = Double.toString(totalR1);
lblTotalRun1.setText(stringTotalR1);
int intJ1R2 = Integer.parseInt(txtJ1R2.getText());
int intJ2R2 = Integer.parseInt(txtJ2R2.getText());
int intJ3R2 = Integer.parseInt(txtJ3R2.getText());
int intJ4R2 = Integer.parseInt(txtJ4R2.getText());
int intJ5R2 = Integer.parseInt(txtJ5R2.getText());
int intJ6R2 = Integer.parseInt(txtJ6R2.getText());
double[] r2Array = {intJ1R2, intJ2R2, intJ3R2, intJ4R2, intJ5R2, intJ6R2};
for (int i=0; i<r2Array.length; i++)
{
for (int j = 1; j <(r2Array.length-i); j++)
{
if (r2Array[j-1]>=r2Array[j])
{
temp=r2Array[j-1];
r2Array[j-1] = r2Array[j];
r2Array[j] = temp;
}
}
}
double totalR2 = (r2Array[1] + r2Array[2] + r2Array[3] + r2Array[4])/4;
String stringTotalR2 = Double.toString(totalR2);
lblTotalRun2.setText(stringTotalR2);
Create a method with the following signature:
public double[] bubbleSort(double[] array){
//move your sorting code here, and change array's name to array
return sortedArray;
}
Create a class and a method and then invoke the method from the main method
public class BubbleSort
{
public void bubbleSort(int value1, int value2, int value3, int value4, int value5, int value6) {
double[] r1Array = {value1, value2, value3, value4, value5, value6};
double temp;
for (int i=0; i<r1Array.length; i++)
{
for (int j = 1; j <(r1Array.length-i); j++)
{
if (r1Array[j-1]>=r1Array[j])
{
temp=r1Array[j-1];
r1Array[j-1] = r1Array[j];
r1Array[j] = temp;
}
}
}
double totalR1 = (r1Array[1] + r1Array[2] + r1Array[3] + r1Array[4])/4;
String stringTotalR1 = Double.toString(totalR1);
lblTotalRun1.setText(stringTotalR1);
}
public static void main(String[] args)
{
BubbleSort bubbleSort = new BubbleSort();
int intJ1R1 = Integer.parseInt(txtJ1R1.getText());
int intJ2R1 = Integer.parseInt(txtJ2R1.getText());
int intJ3R1 = Integer.parseInt(txtJ3R1.getText());
int intJ4R1 = Integer.parseInt(txtJ4R1.getText());
int intJ5R1 = Integer.parseInt(txtJ5R1.getText());
int intJ6R1 = Integer.parseInt(txtJ6R1.getText());
bubbleSort.bubbleSort(intJ1R1,intJ1R1,intJ1R1,intJ1R1,intJ1R1,intJ1R1);
int intJ1R2 = Integer.parseInt(txtJ1R2.getText());
int intJ2R2 = Integer.parseInt(txtJ2R2.getText());
int intJ3R2 = Integer.parseInt(txtJ3R2.getText());
int intJ4R2 = Integer.parseInt(txtJ4R2.getText());
int intJ5R2 = Integer.parseInt(txtJ5R2.getText());
int intJ6R2 = Integer.parseInt(txtJ6R2.getText());
bubbleSort.bubbleSort(intJ1R2,intJ1R2,intJ1R3,intJ1R4,intJ1R5,intJ1R6);
}
}
You can define the integer parameters inside the bubbleSort method itself once however since I don't know from What datatype you are converting to Integer hence have written it twice in main method itself
public static void main(String[] args)
{
BubbleSort bs = new BubbleSort(); //name of your class instead of BubbleSort
double[] r1Array = {intJ1R1, intJ2R1, intJ3R1, intJ4R1, intJ5R1, intJ6R1};
double[] r2Array = {intJ1R2, intJ2R2, intJ3R2, intJ4R2, intJ5R2, intJ6R2};
double[] sortedR1 = bs.bubbleSort(r1Array);
double[] sortedR2 = bs.bubbleSort(r2Array);
}
public double[] bubbleSort(double[] array){
double temp;
for (int i=0; i<array.length; i++)
{
for (int j = 1; j <(array.length-i); j++)
{
if (array[j-1]>=array[j])
{
temp=array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
return array;
}
I'm having a problem adding up the method output and putting it into another method and then printing it. My error is that it keeps printing out the first run of the program. Is there a way to record the multiple runs of the method and put it into a double?
public static void main(String[] args)
{
AnnualUse[] fills = {new AnnualUse (1, 1, 9000, 9420, 16.0, 3.11),
new AnnualUse (2, 30, 9420, 9840, 16.0, 3.08),
new AnnualUse (3, 60, 9840, 10240, 15.23, 3.06)};
String [] oP = new String [3];
int diMin=0;
int diM=0;
double MPin=0;
double MPax=0;
double Primin=0;
double Primax=0;
double roundoff1=0;
double roundoff2=0;
int minDist = Integer.MAX_VALUE;
int maxDist = Integer.MIN_VALUE;
double minMPG = Double.MAX_VALUE;
double maxMPG = Double.MIN_VALUE;
double minPri = Double.MAX_VALUE;
double maxPri = Double.MIN_VALUE;
for (int index=0; index<fills.length; index++)
{
fills[index].calcDistance();
fills[index].calcMPG();
fills[index].calctotalCost();
fills[index].totalDist();
fills[index].totalMPG();
fills[index].totalcost();
}
for (int i = 0; i < fills.length; i++) {
if (fills[i].getDist() < minDist){
minDist = fills[i].getDist();
diMin = minDist ;
}
if (fills[i].getDist() > maxDist) {
maxDist = fills[i].getDist();
diM = maxDist;
}
if (fills[i].getMPG() <minMPG) {
minMPG = fills[i].getMPG();
MPin = minMPG;
}
if (fills[i].getMPG() > maxMPG) {
maxMPG = fills[i].getMPG();
MPax = maxMPG;
roundoff1= Math.round(MPax * 100.0) / 100.0;
}
if (fills[i].getMoolah() < minPri) {
minPri = fills[i].getMoolah();
Primin = minPri;
roundoff2= roundoff2= Math.round(Primin * 100.0) / 100.0;
}
if (fills[i].getMoolah() > maxPri) {
maxPri = fills[i].getMoolah();
Primax = maxPri;
}
}
System.out.println("Fill Up Days Start Miles End Miles Distance Gallons Used MPG Price Cost");
for ( int index=0; index< oP.length; index++)
{
System.out.printf("%3d %8d %10d %10d %9d %13.1f %8.2f %7.2f %8.2f %n" ,
fills[index].getFill(),fills[index].getDay(),
fills[index].getStart(),fills[index].getEnd(),
fills[index].getDist(), fills[index].getUseofG(),
fills[index].getMPG(), fills[index].getCost(),
fills[index].getMoolah());
}
System.out.println();
System.out.println("Minimum:"+" "+diMin+" "+MPin+" "+roundoff2);
System.out.println("Maximum:"+" "+diM+" "+roundoff1+" "+Primax);
System.out.print("Totals:");
for (int index=0; index<1;index++)
System.out.printf( "%20d %20.2f %10.2f", fills[index].getTotal1(),fills[index].getTotal2(),fills[index].total3());
}
first bit of data, from the file I noticed that it's printing out the first run through but I have no idea why it is not adding the values.This is basically how most of the program is. Sorry for not knowing how to explain most of what is going on, I only know the processes actions and don't know to descriptively describe step by step.
class AnnualUse
{
private int counter,day,ender1, starter1, differance,total1 ;
private double amount, cost,MPG,Moolah, minDist,
maxDist,minMPG,maxMPG,minPrice,maxPrice,total2,total3;
AnnualUse (int numberofFills,int days,int starter,int ender,double useofg, double costofg)
{
counter=numberofFills;
day= days;
starter1=starter;
ender1=ender;
amount=useofg;
cost=costofg;
}
public void calcDistance()
{
differance=ender1 - starter1;
}
public int getDist()
{
return differance;
}
public void calcMPG()
{
MPG=differance / amount;
}
public double getMPG()
{
return MPG;
}
public void calctotalCost()
{
Moolah= amount * cost;
}
public double getMoolah()
{
return Moolah;
}
public int getFill()
{
return counter;
}
public int getDay()
{
return day;
}
public int getStart()
{
return starter1;
}
public int getEnd()
{
return ender1;
}
public double getUseofG()
{
return amount;
}
public double getCost()
{
return cost;
}
public void totalDist()
{
total1=+ differance ;
}
public int getTotal1()
{
return total1;
}
public void totalMPG()
{
total2=+MPG;
}
public double getTotal2()
{
return total2;
}
public void totalcost()
{
total3=+Moolah;
}
public double total3()
{
return total3;
}
}
There is too much here for me to give you a specific answer.
It might be worth it for you to clean up the code as much as you can (format it, tidy it, fix as much as you can, etc) and then post it on Code Review for more detailed feedback.
https://codereview.stackexchange.com/
I'm not going to go through all your code for you but you seem to be asking about totals and averages. To calculate those you just need to loop through your values:
double total1 = 0;
double total2 = 0;
for (MyClass mc: theListOfObjects) {
total1 += mc.getFirstTotal();
total2 += mc.getSecondTotal();
}
System.out.println("Totals: "+total1+", "+total2);
System.out.println("Mean: "+(total1/theListOfObjects.size())+", "+(total2/theListOfObjects.size()));
Instead of having separate methods to trying adding the total I just needed to make a variable and then add up all of the inputs.
int total1= fills[0].getDist()+fills[1].getDist()+fills[2].getDist();
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.
I have been developing an implementation of the neighbourhood algorithm in Java for a physics project I am working on. I'm brand new to Java so I apologize for any idiocy that results.
I have been getting the error
''
incompatible types
found : void
required: java.util.List<VoronoiPoint>
'' on line 22 from the Java compiler in attempting to compile the program shown below. I cannot figure out why the variable ''thelist'' somehow turns into a void when I declared it to be of type List<VoronoiPoint>. If anybody can explain to me what is going on it would be much appreciated!
import java.lang.Double;
import java.util.*;
public class VoronoiTiling
{
public static void main(String args[])
{
Integer n = 10; //Number of dimensions of model parameter space
Integer ns = 20; //Number of points per iteration
Integer nr = 4; //Number of cells to populate
Integer iterations = 5; //Number of iterations
List<VoronoiPoint> thelist = VoronoiList.startlist(ns,n);
//System.out.println(thelist);
//System.out.println(thelist.get(1).misfit);
for (Integer i=0 ; i<thelist.size() ; i++)
{
thelist.get(i).setmisfit();
}
List<VoronoiPoint> orderedlist = Collections.sort(thelist);
Double distance = EuclidianDistance((thelist.get(1)).location,(thelist.get(2)).location);
System.out.println(distance);
}
public static Double EuclidianDistance(Double[] point1, Double[] point2)
{
Double distance=0.0;
for (int i = 0; i < point1.length; i++)
{
distance = distance + Math.pow((point1[i]-point2[i]),2);
}
return Math.sqrt(distance);
}
}
The other classes I used are here:
The VoronoiList class:
import java.util.*;
public class VoronoiList
{
public static List<VoronoiPoint> startlist(Integer ns, Integer n)
{
List<VoronoiPoint> thestartlist = new ArrayList<VoronoiPoint>();
for (int i = 0; i < ns; i++)
{
thestartlist.add(new VoronoiPoint(0.,n));
}
return thestartlist;
}
}
The VoronoiPoint class:
import java.util.Random;
public class VoronoiPoint implements Comparable<VoronoiPoint>
{
Double[] location;
private Random generator = new Random();
Double misfit = -1.;
//***************************************************************
public VoronoiPoint(Double misfit, Integer n)
{
location = new Double[n];
ParameterBoundaries boundaries = new ParameterBoundaries(n);
for(int i = 0; i < n; i++)
{
location[i] = boundaries.getboundaries(2*i)+2*generator.nextDouble();
}
}
//***************************************************************
//public Double[] getlocation()
//{
//return location;
//}
public void setlocationi(Integer i, Double j)
{
location[i] = j;
}
//***************************************************************
public void setmisfit()
{
Integer n = location.length;
Double tempmisfit = 0.0;
for(Integer i = 0; i < n; i++)
{
tempmisfit = tempmisfit + Math.pow((location[i]),2);
}
misfit = Math.sqrt(tempmisfit); // Temporarily just distance to centre
}
//public Double getmisfit()
//{
//return misfit;
//}
public int compareTo(VoronoiPoint b)
{
if (this.misfit<b.misfit) return -1;
else if (this.misfit==b.misfit) return 0;
return 1;
}
}
And the parameter boundaries class:
public class ParameterBoundaries
{
private Double[] boundaries; /*Set to 2n where n is dimensions of parameter space,
* it just makes it easier*/
public ParameterBoundaries(Integer n)
{
boundaries = new Double[2*n];
for(Integer i = 0; i<n; i++)
{
boundaries[2*i] = -1.0;
boundaries[2*i+1] = 1.0;
}
}
public Double getboundaries(Integer i)
{
return boundaries[i];
}
}
Collections.sort(..) sorts the original list. It doesn't return a new list. (Its return type is void)
Your code is wrong. Collections.sort() is an in-place sort function; it modifies the given list argument and returns nothing (void).