I’m working on an assignment for my Intro to Java course and I’m currently stuck trying to sort an array of integers.
I get the values from a point object array, p, and pass them to an int array of the same size, pSize. All I need is the point object’s value of x to be typecast to int and get the array sorted. However, that is not occuring. Here is the code:
import java.util.*;
import java.awt.*;
public class doCheckWin {
// Class Fields
private Point[] p;
private static int pSize;
/*
Class Constructor.
Creates an array of point objects that holds the user's
location of pieces.
*/
public doCheckWin(Point[] p) {
this.p = p;
pSize = p.length;
}
public void checkHorizontal() {
int[] col = new int[pSize];
for(int i=0; i<p.length; i++) {
col[i] = (int)p[i].getX();
}
Arrays.sort(col);
System.out.println(Arrays.toString(col));
}
}
Here’s the method from another classthat passes the point object:
public void checkWin(Point[] p) {
doCheckWin dcw = new doCheckWin(p);
dcw.checkHorizontal();
}
When I print the array to screen, the values are ints…using getX changes them to double but when typecasting to int it’s not working…
The problem is:
- Typecasting the value of
x(ie: 10.0) to an integer does not work. When printing the results out on the screen I still get 10.0. Arrays.sort(col)is not sorting the array.
Sample Output of What I’m Getting
10.0
13.0
12.0
11.0
3.0
What I Want
3
10
11
12
13
Edit: Here’s the code used to print out the array:
Arrays.sort(col);
for(int i=0; i<col.length; i++) {
System.out.println(col[i]);
}
What is the point of your Point object (no pun intended)?
What is the contents of p[]? Is it an array of Point objects like you said? If so, why are you creating a point object from a point object?
It looks like you want to do something like so:
That seem to work for me.
Here is an example:
Which gives: