Client and Object Class outputting values - java

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.

Related

Read data from file, write result into a new file(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");
}

Magic Square Method needs to output if it is a magic square and the sum of rows and columns

I'm working on an assignment that takes a data file with a number matrix and determines if it is a magic square. If it is then it also needs to report the sum of the rows and columns. With the output:
The matrix is a magic square.
The sum of all the rows and columns is 34.
I'm not sure how to go about this with one method, I feel like its asking me to return 2 values. The closest I have came is by adding a System.out.println with the sum at the end of my method when it returns true.
But the issue with that is that my output is backwords:
The sum of all the rows and columns is 34.
The matrix is a magic square.
How do I get the sum when I've only been asked to create one method? Below is my code, the instructor gave the bottom 3 methods so I'm only concerned with the first 2.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class chp8magic
{
public static void main(String args[])
{
int matrix[][] = initMatrix();
printData(matrix);
if (isMagic(matrix)) {
System.out.println("The matrix is a magic square.");
}
else {
System.out.println("Not a magic square");
}
}
public static boolean isMagic(int[][] mat)
{
int n = mat.length;
int nSquare = n*n;
int M = (n*n*(n*n+1)/2)/n;
int sumRow = 0, sumColoumns = 0, sumPriDiag = 0, sumSecDiag = 0;
boolean[] flag = new boolean[n*n];
for(int row = 0; row < n; row++){
sumRow = 0;
sumColoumns = 0;
for(int col = 0; col < n; col++)
{
if( mat[row][col] < 1 || mat[row][col] > nSquare )
return false;
if(flag[mat[row][col]-1] == true)
return false;
flag[mat[row][col]-1] = true;
sumRow += mat[row][col];
sumColoumns += mat[col][row];
}
sumPriDiag += mat[row][row];
sumSecDiag += mat[row][n-row-1];
if(sumRow!=M || sumColoumns!=M)
return false;
}
if(sumPriDiag!=M || sumSecDiag!=M)
return false;
else
return true;
}
public static int[][] initMatrix()
{
int matrix[][];
Scanner filein = null;
try {
filein = new Scanner(new File("matrix.txt"));
int numRows = Integer.parseInt(filein.nextLine());
matrix = new int[numRows][];
parseData(matrix, filein);
filein.close();
return matrix;
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
if(filein != null)
filein.close();
return null;
}
}
public static void parseData(int matrix[][], Scanner in)
{
for(int r = 0; r < matrix.length; r++)
{
String splitLine[] = in.nextLine().split(" ");
matrix[r] = new int[splitLine.length];
for(int c = 0; c < matrix[r].length; c++){
matrix[r][c] = Integer.parseInt(splitLine[c]);
}
}
}
public static void printData(int matrix[][])
{
for(int r = 0; r < matrix.length; r++){
for(int c = 0; c < matrix[r].length; c++){
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
Probably you just need to do:
System.out.println("is magic: " + isMagic);
System.out.ptintln("sum: " + sum);
However this is not really returning the values, just printing them. To return two values there are several options. You could return an object:
public class MagicSquareProperties {
private boolean magic;
private int sum;
public MagicSquareProperties(boolean magic, int sum) {
this.magic = magic;
this.sum = sum;
}
public boolean isMagic() {
return magic;
}
public int getSum() {
return sum;
}
}
// now to return both values: return new MagicSquareProperties(true, 34);
But in my opinion the best solution would be the following:
Create a class MagicSquare.
Add property declarations (e.g. private int sum).
Add a constructor, for example MagicSquare(File file), this constructor reads the file and populates the properties.
Add getters and setters if needed (e.g. getSum())
Execute the main method in another class and call new MagicSquare(...) to create a magic square object. Afterwards you can call the getters on the object whenever you need the value.

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

How to fill a multidimensional array dependant on variables

The program I am working on is a simple shipping program. What I am having difficulty with is populating a multidimensional array factoring in certain variables.
Example
320 items need to be shipped out to 1 receiver using different box sizes.
XL can hold 50 items
LG can hold 20 items
MD can hold 5 items
SM can hold 1 items
Use the least number of boxes so far.
Code
This is my code so far.
import java.util.Scanner;
public class Shipping {
public static void main(String [] args) {
Scanner kbd = new Scanner(System.in);
final int EXTRA_LARGE = 50;
final int LARGE = 20;
final int MEDIUM = 5;
final int SMALL = 1;
String sBusinessName = "";
int iNumberOfGPS = 0;
int iShipmentCount = 0;
displayHeading(kbd);
iShipmentCount = enterShipments(kbd);
int[][] ai_NumberOfShipments = new int [iShipmentCount][4];
String[] as_BusinessNames = new String [iShipmentCount];
for (int iStepper = 0; iStepper < iShipmentCount; iStepper++) {
sBusinessName = varifyBusinessName(kbd);
as_BusinessNames[iStepper] = sBusinessName;
iNumberOfGPS = varifyGPS(kbd);
calculateBoxes(ai_NumberOfShipments[iStepper],iNumberOfGPS, EXTRA_LARGE, LARGE, MEDIUM, SMALL);
}
//showArray(as_BusinessNames);
}
public static void displayHeading(Scanner kbd) {
System.out.println("Red River Electronics");
System.out.println("Shipping System");
System.out.println("---------------");
return;
}
public static int enterShipments(Scanner kbd) {
int iShipmentCount = 0;
boolean bError = false;
do {
bError = false;
System.out.print("How many shipments to enter? ");
iShipmentCount = Integer.parseInt(kbd.nextLine());
if (iShipmentCount < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
bError = true;
}
} while (bError == true);
return iShipmentCount;
}
public static String varifyBusinessName(Scanner kbd) {
String sBusinessName = "", sValidName = "";
do {
System.out.print("Business Name: ");
sBusinessName = kbd.nextLine();
if (sBusinessName.length() == 0) {
System.out.println("");
System.out.println("**Error** - Name is required\n");
} else if (sBusinessName.length() >= 1) {
sValidName = sBusinessName;
}
} while (sValidName == "");
return sValidName;
}
public static int varifyGPS(Scanner kbd) {
int iCheckGPS = 0;
int iValidGPS = 0;
do {
System.out.print("Enter the number of GPS receivers to ship: ");
iCheckGPS = Integer.parseInt(kbd.nextLine());
if (iCheckGPS < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
} else if (iCheckGPS >= 1) {
iValidGPS = iCheckGPS;
}
} while(iCheckGPS < 1);
return iValidGPS;
}
public static void calculateBoxes(int[] ai_ToFill, int iNumberOfGPS) {
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++)
}
//public static void showArray( String[] ai_ToShow) {
// for (int iStepper = 0; iStepper < ai_ToShow.length; iStepper++) {
// System.out.println("Integer at position " + iStepper + " is " + ai_ToShow[iStepper]);
// }
//}
}
Change your definition of calculateBoxes() to also take an array that represents the volume of each of the boxes (in your case this will be {50, 20, 5, 1}:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
// while the remaining items to pack is greater than the current box size
while(iNumberOfGPS >= boxVolumes[iStepper]) {
// increment the current box type
ai_ToFill[iStepper]++;
// subtract the items that just got packed
iNumberOfGPS -= boxVolumes[iStepper];
}
}
}
Another way of calculating this (using / and % instead of a while loop) would be:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
if(iNumberOfGPS >= boxVolumes[iStepper]) {
// calculate the number of boxes that could be filled by the items
ai_ToFill[iStepper] = iNumberOfGPS/boxVolumes[iStepper];
// reset the count of items to the remainder
iNumberOfGPS = iNumberOfGPS%boxVolumes[iStepper];
}
}
}

Collections.sort compile error - incompatible types

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).

Categories

Resources