问题
I have an array of numbers and would like to retrieve one of the values from location "index". I've looked at the Java documentation http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Array.html but my code still isn't compiling.
here is my method:
public class ConvexPolygon implements Shape
{
java.awt.Point[] vertices;
public ConvexPolygon(java.awt.Point[] vertices)
{
this.vertices = vertices;
this.color = color;
this.filled = filled;
}
java.awt.Point getVertex(int index)
{
Point vertex;
vertex = get(Point vertices, int index);
}
I have numbers in an array representing Points. The value index is going to be the location of the array verities. What can I do to make this work? Thanks !
回答1:
In Java, array indexes are denoted by the square brackets. You can replace your get(vertices, index) call like so:
vertex = vertices[index];
In looking at your code, it appears you are coming from a language that defines a global get() function for such operations. Be aware that, in Java, there are no global functions. Each class you create defines its own functions, and any function call without an object or class preceding it is assumed to be defined in the local class.
So, your call to get(Point[], int) could work only if you define that function on this class:
public Point get(Point[] vertices, int index) {
return vertices[index];
}
Or define it statically on another class and precede the call with the class name:
public class PointArrayHelper {
public static Point get(Point[] vertices, int index) {
return vertices[index];
}
}
PointArrayHelper.get(vertices, index);
Now, be warned that I don't think you should do either of these! I just thought it might help you understand Java a little better.
回答2:
I think you're just looking for:
Point vertex = vertices[index];
At least - if you're not looking for that, please expand on what the difference is between using the array index and what you do want :)
回答3:
Hope it works!
java.awt.Point getVertex(int index)
{
return vertices[index];
}
来源:https://stackoverflow.com/questions/2150064/java-getting-a-value-from-an-array-from-a-defined-location