Declaration of variable size dynamic array of objects in processing - java

I want to ask a question about Processing. I have a user defined object class, Point, and it have two data members x and y both declared as float. I have another class Recognizer. I need to create the constructor of Recognizer and inside it define the object of Point[] point0, Point[] point1, etc... dynamically.
Point [] point0={new Point(137,139),new Point(50,63),..., new Point(78,5)};
so is point1[],point2[],...,pointn[]
How else can I add the values into point0 having the values of corresponding x and y coordinate.
Also note that the size of each object point1,point2,..., pointn are different.
How can I achieve the above goal?

How about using a 2 dimensional array ?
Point [] points0={new Point(137,139),new Point(50,63),new Point(78,5)};
Point [] points1={new Point(147,139),new Point(60,63),new Point(79,5)};
Point [] points2={new Point(157,139),new Point(70,63),new Point(80,5)};
void setup(){
Point[][] pointLists = {points0,points1,points2};
Recognizer r = new Recognizer(pointLists);
}
class Point{
float x,y;
Point(float x,float y){
this.x = x;
this.y = y;
}
String toString(){
return "Point("+x+","+y+")";
}
}
class Recognizer{
Point[][] data;
Recognizer(Point[][] data){
this.data = data;
for(int i = 0 ; i < data.length; i++){
println("processing points list" + i);
for(int j = 0; j < data[i].length; j++){
println("processing point["+j+"] of list " + i + " : "+data[i][j]);
}
}
}
}
and the ArrayList version:
import java.util.Arrays;
ArrayList<Point> points0 = new ArrayList<Point>(Arrays.asList(new Point[]{new Point(137,139),new Point(50,63),new Point(78,5)}));
ArrayList<Point> points1 = new ArrayList<Point>(Arrays.asList(new Point[]{new Point(147,139),new Point(60,63),new Point(79,5)}));
ArrayList<Point> points2 = new ArrayList<Point>(Arrays.asList(new Point[]{new Point(157,139),new Point(70,63),new Point(80,5)}));
void setup(){
ArrayList<ArrayList<Point>> pointLists = new ArrayList<ArrayList<Point>>();
pointLists.add(points0);
pointLists.add(points1);
pointLists.add(points2);
Recognizer r = new Recognizer(pointLists);
}
class Point{
float x,y;
Point(float x,float y){
this.x = x;
this.y = y;
}
String toString(){
return "Point("+x+","+y+")";
}
}
class Recognizer{
ArrayList<ArrayList<Point>> data;
Recognizer(ArrayList<ArrayList<Point>> data){
this.data = data;
for(int i = 0 ; i < data.size(); i++){
println("processing points list" + i);
for(int j = 0; j < data.get(i).size(); j++){//write this in a nicer way, too many get calls, might want a reusable variable here
println("processing point["+j+"] of list " + i + " : "+data.get(i).get(j));
}
}
}
}

Related

Array required but int found

What's wrong with my progam?
public class Square{
public int x;
public Square() {
int x[] = new int[10];
int y;
x[0] = 7;
}
public void root() {
for (int i = 0; i < 10; i++) {
x[i+1] = x[i] - (Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5));
System.out.println(x[i + 1]);
}
}
}
I don't get what's wrong, my for loop does not seem to be working and it keeps on displaying the error for some reason. Could someone help me figure this out?
Okay, I wrote this program now:
public class Square
{
public double x[];
public void root()
{
double x[] = new double[10];
x[0]=7;
for(int i=0; i<8; i++)
{
x[i+1]=x[i]-(Math.pow(x[i]-2.5,2))/(2*(x[i]-2.5));
System.out.println(x[i+1]);
}
}
}
And it is showing this output:
3.625
3.0625
2.78125
2.640625
2.5703125
2.53515625
2.517578125
java.lang.NullPointerException
at Square.root(Square.java:14)
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at Square.root(Square.java:11)
I don't know why I'm getting these errors. Also, the answer should be 6.25 at some point. But, it doesn't show that output.
Your constructor has a local variable int[] x which is disarded at the end of the constructor.
Try this:
public class Square{
// initialize to array of ten ints
public int x[] = new int[10];
public Square() {
x[0] = 7;
}
public void root() {
for (int i = 0; i < 10; i++) {
x[i+1] = x[i] - (Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5));
System.out.println(x[i + 1]);
}
}
}
Edit: The int y is local to the constructor, it is discarded at the end of the constructor scope, too.
This is because you have defined x previously as just an int, instead of an array of ints.
Try this:
public class Square {
public int x[];
public Square() {
this.x = new int[10];
int y;
x[0] = 7;
}
public void root() {
for(int i = 0; i < 10; i++) {
x[i + 1] = x[i] - (Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] -2.5));
System.out.println(x[i + 1]);
}
}
}
Here is the commented code explaining the problem :
public class Square
{
// Here, x is defined as an attribute of class Square, of type int
public int x;
public Square()
{
// Here, x is locally defined as a local variable, of type int[]
// It shadows the attribute x. This is considered as a bad practice.
int x[] = new int[10];
int y;
// Here, x is the local variable, of type int[]. It IS an array so
// this line is valid.
x[0]=7;
}// From this point, the local variable x is not defined anymore
// (that is the point of a local variable)
Now here :
public void root()
{
for(int i=0; i<10; i++)
{
// Here, x is referencing the attribute of class Square, which is an int
// But you try to access it as if it was and int[]
x[i+1]
First you must declare x as an array:
public int[] x;
notice that the java style is not int x[];
Then inside Square() you have to initialize x like this:
x = new int[10];
Finally, this:
(Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5))
returns a double so you have to cast it to int:
x[i+1] = x[i] - (int) ((Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5)));
So your code should be:
public int[] x;
public void Square() {
x = new int[10];
x[0] = 7;
}
public void root() {
if (x == null)
Square();
for(int i = 0; i < x.length - 1; i++) {
x[i+1] = x[i] - (int) ((Math.pow(x[i] - 2.5, 2)) / (2 * (x[i] - 2.5)));
System.out.println(x[i+1]);
}
}
Inside the loop you are accessing the i + 1 item so the counter of the loop must take values up to x.length - 2, this is why I have in the code: i < x.length - 1.
I have removed the declaration of y from Square() as it is not used.
public class Square
{
public double x[];
public Square()
{
this.x = new double[10];
x[0]=7;
}
public void root()
{
System.out.println(x[0]);
for(int i=1; i<10; i++)
{
x[i]=x[i-1]-(Math.pow(x[i-1]-2.5,2))/(2*(x[i-1]-2.5));
System.out.println(x[i]);
}
}
}
Try use this code
public class Square
{
public double x[];
public void root()
{
x = new double[10];
x[0]=7;
for(int i=1; i<10; i++)
{
x[i]=x[i-1]-(Math.pow(x[i-1]-2.5,2))/(2*(x[i-1]-2.5));
System.out.println(x[i]);
}
}
}

Array Sort Stops Too Soon

I'm trying to create two classes, one to define a point and another for array operations. I'm trying to create a method to sort an array of coordinates in ascending order based on y coordinates. I've tried following examples, but I keep running into a runtime error where the array is only partially sorted.
public class Point
{
private double x;
private double y;
public Point(double x_coord, double y_coord)
{
x = x_coord;
y = y_coord;
}
public boolean lessThan(Point anotherPoint)
{
if(y < anotherPoint.y)
{
if(x < anotherPoint.x)
{
return true;
}
}
return false;
}
}
public class PointArray
{
private Point[] points = new Point[count];
public PointArray(double[] doubleArray)
{
if(doubleArray.length % 2 == 0)
{
for(int i = 0, j = 0; i < 3; i++, j += 2)
{
double x = doubleArray[j];
double y = doubleArray[j + 1];
points[i] = new Point(x, y);
}
}
else
{
System.out.println("Error: The given array must be even.");
System.exit(0);
}
}
public void sort()
{
double x = 0;
double y = 0;
Point newPoint = new Point(x, y);
Point temp = new Point(x, y);
for (int i = 0; i < points.length - 1; i++)
{
for(int j = i + 1; j < points.length; j++)
{
int minIndex = i;
if(points[minIndex].lessThan(points[j]) == false)
{
temp = points[minIndex];
points[minIndex] = points[j];
points[j] = temp;
}
}
}
}
This code causes the array {5.6, 7.1, 4.9, 13.17, 9.3, 2.9} to first be stored as ordered pairs {(5.6, 7.1), (4.9, 13.17), (9.3, 2.9)}. but it does not sort them properly. After the first and third points are swapped, the second and third are not, even though the y coordinate of the third is smaller.
[(9.3, 2.9), (4.9, 13.17), (5.6, 7.1)]
EDIT: Another issue appeared related to the same assignment. This method is supposed to take two PointArray objects and compare them for equality by the x and y components. My idea was to sort both arrays and then compare the components using a method in the Point class, but I'm not sure how to define each PointArray in terms of an (x, y) point.
public boolean equals(Point anotherPoint)
{
if(x == anotherPoint.x && y == anotherPoint.y)
{
return true;
}
return false;
}
public boolean equals(PointArray anotherPointArray)
{
double x = 0;
double y = 0;
double xAnother = 0;
double yAnother = 0;
Point newPoint = new Point(x, y);
Point newAnotherPoint = new Point(xAnother, yAnother);
anotherPointArray.sort();
for(int i = 0; i < points.length; i++)
{
for(int j = 0; i < points.length; j++)
{
if(newPoint.equals(newAnotherPoint))
{
return true;
}
}
}
return false;
}
Your current lessThan method will give true only if both x and y are smaller. To sort by y alone use
public boolean lessThan(Point anotherPoint)
{
return y < anotherPoint.y;
}

Classes and 2 Dimension Arrays

The code I am working with is below. I feel like this should be simple, but I'm having an incredibly hard time focusing this week and need some help.
I'm not able to properly set the values for pt.x or pt.y in the nested for loops. IDEA is telling me that the symbol can't be resolved. The class is identified from another java file in the package that only identifies that class. it is as follows:
public class pointClass {
class point{
int x;
int y;
int z;
}
}
(Adding text to demonstrate these are 2 separate files)
This is for a class assignment, but I'm not sharing the whole assignment, just what I need help with. I'm trying to learn, not have things done for me.
public class main {
public static void main (String args[]){
ArrayList<pointClass.point> pointlist = new ArrayList<>();
//Creating map
int row = 40;
int col = 40;
int [][] bigarray = new int [row] [col];
//iterating through map
for (int i = 0; i < row; i++;){
for (int j=0; j< col; j++){
pointClass pt = new pointClass.point;
pt.x = row;
pt.y = col;
pt.z = ;//RNG HERE//
}
}
How do I need to more properly identify these class attributes? For context,this code cretes a 40x40 array and will assign a random value to each number. Another code stanza will be added to print the 2D array.
There doesn't seem to be a need for a Nested class here. Consider just using the following:
public class Point {
int x;
int y;
int z;
}
Now let's take a look at your syntax errors. Most are fairly simple, but deserve discussion nonetheless.
public class Main {
public static void main(String args[]){
ArrayList<Point> pointlist = new ArrayList<>(); //Now that we aren't using a nested class, Just <Point>
//Creating map
int row = 40;
int col = 40;
int [][] bigarray = new int [row] [col];
//iterating through map
for (int i = 0; i < row; i++){ //No semicolon after i++
for (int j=0; j< col; j++){
Point pt = new Point(); //Calling a constructor is a method, hence ()
pt.x = j; //You probably mean j and k here, not row and col (which don't change)
pt.y = k;
pt.z = 0;//RNG HERE// //Not sure what you mean here, but you can set pt.z to whatever you want
//You created pointlist, but never add to it. Did you mean to?
pointlist.add(pt);
}
}
}
}
I've just tested the above and it compiles and runs correctly. That said, you can do a lot better stylistically. Here are some tips.
Class names start with a capital letter. Point, not point. PointClass, not pointClass.
Non-final / mutable fields should be private. Thus your Point class, while correct, is fairly bad practice (the reasons for which are very well documented elsewhere). Consider using the following alternative:
public class Point {
private int x;
private int y;
private int z;
public Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getX() { return x; }
public int getY() { return y; }
public int getZ() { return z; }
}

Error with Bresenham's line algorithm

I'm trying to fill a matrix with stars (*) to draw Bresenham's line, but when i'm printing out the thing the matrix is only filled with one star i don't know whats wrong. Language is Java
public class PtLine extends VectorObject{ // inherites from another class
private int bx;
private int by;
private int delX;
private int delY;
public PtLine(int id,int x,int y,int bx,int by){
super(id,x,y);
this.bx = bx;
this.by = by;
this.delX = this.bx-x;
this.delY = this.by-y;
}
public void draw ( char [][] matrix ){ // filling the martic with stars
int D = 2*delY - delX;
matrix[x][y] = '*';
int j = y;
for (int i=x+1;i==bx;i++){
if(D > 0){
j+=1;
matrix[i][j]='*';
D = D + (2*delY-2*delX);
}
else{
matrix[i][j]='*';
D = D + (2*delY);
}
}
}
}
The following code is when i'm trying to print out the matrix
class Question3{
public static void main ( String args [] ){
char[][] matrix = new char[20][20];
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
matrix[y][x] = ' ';
}
}
PtLine n = new PtLine(6,6,6,13,13);
n.draw(matrix);
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
System.out.print(matrix[x][y]);
}
System.out.println();
}
}
}
It's likely that you have to change i==bx with i!=bx:
public void draw ( char [][] matrix ){ // filling the martic with stars
int D = 2*delY - delX;
matrix[x][y] = '*';
int j = y;
for (int i=x+1;i!=bx;i++){ // here
...
}
}
The for loop continues while this condition is true. In your code loop finishes immediately at start, before the first iteration, because this condition is false.

Finding the closest point

In my program, I am attempting to find the closest point from the starting position (0,0), then "move" again to the next point. The points are read in through a file. The next point I am trying to move to is the "closest" point. I use the Pythagorean Theorem to find the distance. But what can I do to "check" the point I am going to to determine if I have already have visited it. For instance, if the point is 0,0, and then it goes to 1,1, how do check to "tell" the program that 0,0 is no longer an option?
public class PointsNStuff {
public static void main(String [] args) {
final int P = StdIn.readInt();
double [] x = new double[P];
double [] y = new double[P];
double [] visit= new double[P]; //Set an array that stores points that have been visited already
double [] math= new double[P]; //Set an array that stores the distance to all the points
for( int i= 0; i< P; i++){ //Store the values from the text file
x[i] = StdIn.readDouble();
y[i] = StdIn.readDouble();
}
double lowX = x[0];
double lowY = y[0];
double highX = x[0];
double highY = y[0];
//Find the lowest X and the lowest Y values:
for (int i = 0; i < P; i++){
if (lowX > x[i])
lowX = x[i];
}for (int i = 0; i < P; i++){
if (lowY > y[i])
lowY = y[i];
}
for (int i = 0; i < P; i++){
if (highX < x[i])
highX = x[i];
}
for (int i = 0; i < P; i++){
if (highY < y[i])
highY = y[i];
}
System.out.println(lowX + " " + lowY);
System.out.println(highX + " " + highY);
System.out.println("");
System.out.println(P);
//Determine the closest point
double xCoord=0.0;
double yCoord=0.0;
double dist = -1.0;
for (int i= 0; i < P; i ++){ //Repeat entire section for all P (number of points)
for (int j = 0; j < P; j++){ //Find the distance between current point and all other points. Go through all points (do the math).
xCoord = x[j]; // # x point
yCoord = y[j]; // # y point
double save= Math.sqrt( ( (xCoord+x[j]) * (xCoord+x[j]) ) + ( (yCoord + y[j]) * (yCoord + y[j]) ) ); //Pythagorean theorem
save = math[j]; //store the distance in the array slot
}
for (int j = 0; j < P; j++){
if (dist < math[j]){
dist = math[j];
//What boolean check can I put here to double check whether I have visited this point already?
xCoord = x[j]; // set the two points to what number they should be at.
yCoord = y[j];
}
}
System.out.println(xCoord + " " + yCoord);
}
}
}
I have not used any points into the Array I named "visit". Any and all help is appreciated! Thanks!
Use ArrayList to Store points,
ArrayList<Double> x = new ArrayList<Double>();
ArrayList<Double> y = new ArrayList<Double>();
add points to arraylist,
for( int i= 0; i< P; i++){ //Store the values from the text file
x.add(StdIn.readDouble());
y.add(StdIn.readDouble());
}
select point from araylist,
x.get(i); insted of x[i];
y.get(i); insted of y[i];
and remove already used points,
x.remove(new Double(used_x_value));
y.remove(new Double(used_y_value));
see Class ArrayList
What you have here is a perfect candidate for encapsulation! I would start by thinking about another object to encapsulate the 'point' concept you keep referring to:
class Point {
private final double x;
private final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
One minor caveat: this assumes that you will not have duplicate x,y pairs in the input file. If you do, you may need to override hashcode and equals. But if not, this should do it. Then you can put these Points into a data structure ( see HashSet ) like this:
import java.util.Set;
import java.util.HashSet;
public class PointsNStuff {
public static void main(String args[]) {
Set<Point> pointsVisited = new HashSet<>();
//when you visit a point, put it in the set like this
//the numbers are just for example
Point currentPoint = new Point(10.0, 12.0);
pointsVisited.add(currentPoint);
//now in the future you can check if you 'visited' this point
if(!pointsVisited.contains(currentPoint)) {
System.out.println("Haven't been to current point yet...");
}
}
}

Categories

Resources