java使用迭代器对象循环throuh arraylist并检查它是否高于某个值
我有一个静态方法,我需要完成它
我要做的是使用迭代器检查y坐标是否大于最大值,并返回该值。这是我现在拥有的
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;
}
当我运行代码时,会出现一个语法错误:
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
# 1 楼答案
points是一个列表,因此不能对其调用getY()。您需要首先从对pointIterator的调用中获取Point对象。然后对其调用getY()方法
您还可以通过使用流和删除整个样板代码来实现相同的功能
# 2 楼答案
将
next()
的结果存储在变量中检查当前
highestPoint
是否为null
。如果是,请将currentPoint
设置为最高值:否则,将最高点与电流进行比较:
不需要
int highest
。你的最终结果是: