I have a static method and I am required to complete it.
What I have to do is use an Iterator to check if the y coordinate is greater than highest value and return that value. Here's what I have now.
import java.awt.*;
public static Point highestPoint(List<Point> points) {
Iterator<Point> pointIterator = points.iterator();
int highest = 0;
Point highestPoint = null;
while (pointIterator.hasNext()) {
pointIterator.next()
if (points.getY() > highest) {
highest = points.get(Y);
}
}
return highestPoint;
}
When I run my code, I get a syntax error saying this:
Main.java:12: error: cannot find symbol
if (points.getY() > highest) {
^
symbol: method getY()
location: variable points of type List<Point>
Main.java:13: error: cannot find symbol
highest = points.getY();
^
symbol: method getY()
location: variable points of type List<Point>
2 errors
points is a List and you cannot hence call getY() on it. You need to get the Point object first from the call to pointIterator.next() and then call getY() method on it.
while (pointIterator.hasNext()) {
Point point = pointIterator.next();
if (point.getY() > highest) {
highest = point.get(Y);
}
}
You can also achieve the same using streams and by removing the entire boilerplate code
Point highest = points.stream().max((p1, p2) -> p1.getY() > p2.getY() ? 1 : -1).get();
Store the result of next()
in a variable
Point currentPoint = pointIterator.next();
Check if the current highestPoint
is null
. If so, set the currentPoint
as the highest:
if(highestPoint == null)
highestPoint = currentPoint;
Otherwise, compare the highest point to the current:
if(highestPoint == null)
highestPoint = currentPoint;
else if(highestPoint.getY() < currentPoint.getY())
highestPoint = currentPoint;
No need for int highest
. Your final result would be:
public Point highestPoint(List<Point> points) {
Point highestPoint = null;
Iterator<Point> pointIterator = points.iterator();
while(pointIterator.hasNext()) {
Point currentPoint = pointIterator.next();
if(highestPoint == null || highestPoint.getY() < currentPoint.getY())
highestPoint = currentPoint;
}
return highestPoint;
}
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.