# How do I place these numbers into an array

Printable View

• 07-18-2009, 03:36 PM
mainy
How do I place these numbers into an array
Hello,

I am struggling with a fairly simple problem which I hope you can help with. I am working on a some code but there is a small part of it which I can't seem to get to work.

I have two classes. I want to enter details into one, which will place those details into an array which can then be accessed.

Class one:
Code:

public class Triangle {

int x, y, l;
int[] cx;
int[] cy;

public Triangle(int x, int y, int l) {
this.x = x;
this.y = y;
this.l = l;
}

public void cords(){
cy[0] = x;
cx[1] = x+10;
cx[2] = x+20;

cy[0] = y;
cy[1] = y+20;
cy[2] = y;

}
}

Then I have a class to test it:
Code:

public class Test {

public static void main(String[] args) {

Triangle tos = new Triangle(100, 200, 3);

System.out.println(tos.cy[0]);

}
}

But instead of getting the 200 print out, I get quite a few errors. Please help
• 07-18-2009, 05:53 PM
hardwired
Before you can use an array you must instantiate it:
Code:

int[] x;              // declaration
int[] y = new int[4];  // declaration and instantiation

Code:

public class TriangleRx {

int x, y, l;
int[] cx;
int[] cy;

public TriangleRx(int x, int y, int l) {
this.x = x;
this.y = y;
this.l = l;
System.out.println("cx = " + cx + "  cy = " + cy);
}

public void cords() {
cy[0] = x;
cx[1] = x+10;
cx[2] = x+20;

cy[0] = y;
cy[1] = y+20;
cy[2] = y;
}

public static void main(String[] args) {
TriangleRx test = new TriangleRx(2, 3, 5);
//        test.cords();
}
}

• 07-19-2009, 06:57 PM
Harpreet1111
u r using the array without instantiating it. just add

cx=new int[size of array];
cy=new int[]size of array];

in constructor and the job is done......