All the methods here are correct, but my problem is that i have to find a part in the parts array that has a certain weight. So After i do the getweight method I think i have to call that. But the last part of the code is what i have a problem with. It starts with the line public Part getPartWithWeight (int weight){
class Robot {
Part[] parts;
public Robot () {// assume these are right}
}
public void addPart(Part p) { // assume these are right}
}
class Part {
// Class details not shown
public double getWeight() {//... }
}
public int getPartnum() {//...}
}
public String getMaterial() {//...}
}
public Part getPartWithWeight (int weight){
for(int i = 0; i < parts.length; i ++){
if (parts[i].weight == weight) {
return parts[i];
}
}
Well, here's the "works-out-of-the-box" version.
Step 1 Write a comparator.
class PartComparator implements java.util.Comparator<Part> {
@Override
public int compare(Part part1, Part part2) {
return part1.weight - part2.weight;
}
public final static PartComparator instance = new PartComparator();
}
The comparator class should be static if you declare it inside Part (which is what I would suggest).
Step 2 Use the comparator
public Part getPartWithWeight (int weight){
Part pivot = new Part();
pivot.weight = weight;
int idx = Arrays.binarySearch(parts, pivot, PartComparator.instance);
return parts[idx];
}
if (parts[i].weight == weight)
should say
if (parts[i].getWeight() == weight)
You should use getWeight() because that's the method defined in the Parts class. Also if you're problem is getting the parts array from the robot class and using it in the part class then you should just pass it as a parameter.
public Part getPartWithWeight (int weight, Part[] parts){
for(int i = 0; i < parts.length; i ++){
if (parts[i].getWeight() == weight) {
return parts[i];
}
}
}
Then when you call the method getPartWithWeight() make sure you put the array in there too.
EDIT: Also per Ray Cheng's comment, the weight you're looking for is supposed to be an int but your getWeight() method returns a double.... so either your getWeight() should return an in or you should typecast it as an int before making the comparison. Be aware that if you typecast it as an int you will lose some precision. It would be better to fix your getWeight() so it returns a double like you need it to.
To implement a binary search, you first need to cut the array in half and then decide which half you want to begin the search. Then you cut the halved array in half again and repeat...
Unless you want to implement your own, but looks like there is a built-in one you can call.
http://docs.oracle.com/javase/7/docs/api/index.html?java/util/Arrays.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.