【发布时间】:2015-10-13 16:58:43
【问题描述】:
所以我正在尝试编写一个方法来返回具有最大区域的对象的索引。这是我目前的方法
private static int findPositionLargestObject(ArrayList < GeometricObject > geoList) {
int maxIndexC = 0;
int maxIndexR = 0;
for (GeometricObject o: geoList) {
for (int i = 1; i < geoList.size(); i++) {
if (o instanceof Rectangle) {
if (((Rectangle) geoList.get(i)).getArea() > ((Rectangle) geoList.get(maxIndexR)).getArea()) {
maxIndexR = i;
}
}
if (o instanceof Circle) {
if (((Circle) geoList.get(i)).getArea() > ((Circle) geoList.get(maxIndexC)).getArea()) {
maxIndexC = i;
}
}
}
}
if (maxIndexC > maxIndexR) {
return maxIndexC;
} else return maxIndexR;
}
但是,当我运行此方法时,我收到错误消息 rectangle can't be cast to circle。我之所以有两个不同的 if 语句,是因为圆形和矩形对象的 getArea 方法分别不同。任何想法为什么我会收到此消息,谢谢!
这是我的公开课
public class hw2redo
{
public static void main(String[] args) throws FileNotFoundException {
GeometricObject g = null;
File diskFile = new File("file.txt");
Scanner diskScanner = new Scanner(diskFile);
ArrayList<GeometricObject> list = new ArrayList<GeometricObject>();
while(diskScanner.hasNext()){
String geolist = diskScanner.nextLine();
g = recreateObject(geolist);
list.add(g);
}
diskScanner.close();
/* while (diskScanner.hasNext()) {
String list = diskScanner.nextLine();
g = recreateObject(list);
}
diskScanner.close();*/
showObjects(list);
findPositionLargestObject(list);
}
private static GeometricObject recreateObject(String data) {
String[] list = data.split(",");
String geoObject = list[0];
if (geoObject.equals("Circle")) {
String color = list[1];
boolean filled = Boolean.valueOf(list[2]);
double radius = Double.valueOf(list[3]);
return new Circle(radius, color, filled);
}
if (geoObject.equals("Rectangle")) {
String color = list[1];
boolean filled = Boolean.valueOf(list[2]);
double height = Double.valueOf(list[3]);
double width = Double.valueOf(list[4]);
return new Rectangle(width, height, color, filled);
}
return null;
}
private static void showObjects(ArrayList<GeometricObject> list) {
for(GeometricObject o : list) {
if ( o instanceof Circle)
{
System.out.println(o);
((Circle) o).printCircle();
System.out.println("");
}
if ( o instanceof Rectangle)
{
System.out.println(o);
((Rectangle) o).printRectangle();
System.out.println("");
}
}
}
private static int findPositionLargestObject(ArrayList<GeometricObject> geoList) {
int maxIndexC = 0;
int maxIndexR = 0;
for(GeometricObject o : geoList)
{
for (int i = 1; i < geoList.size(); i++) {
if ( o instanceof Rectangle)
{
if (((Rectangle) geoList.get(i)).getArea() > ((Rectangle) geoList.get(maxIndexR)).getArea()) {
maxIndexR = i;
}
}
if ( o instanceof Circle)
{
if (((Circle) geoList.get(i)).getArea() > ((Circle) geoList.get(maxIndexC)).getArea()) {
maxIndexC = i;
}
}
}
}
if (maxIndexC > maxIndexR)
{
return maxIndexC;
}
else
return maxIndexR;
}
}
【问题讨论】:
标签: java object casting dynamic-arrays