好的,伙计们,这段代码是我的作业的一部分,我要实现一个 equals() 方法来检查两条线是否相等,如果两个端点相同,则两条线被定义为相等。但是我无法检查它,因为当我在这里按原样运行程序时,它的空白就像数组列表为空一样。我的问题是:我是否需要更改通过文件读取的循环,或者我是否需要取消注释初始数组并对arrayList 做一些事情?
任何帮助将不胜感激!
//Line[] lines;
ArrayList<Line> lines;
Scanner reader;
public MyDrawing()
super();
this.setPreferredSize(new Dimension(500,500));
}
/**
* Reads the file and builds an array of Line objects.
*
* @param fileName The name of the file that contains the lines
* @throws Exception
*/
public void read( File fileName ) throws Exception
{
reader = new Scanner(fileName);
//----------------
// Change to Arraylist. Make the name of the arraylist "lines" so that code in paintComponent works.
//---------------------
//Have to read the first number before starting the loop
int numLines = reader.nextInt();
//lines = new Line[numLines];
ArrayList<Line>lines = new ArrayList<Line>();
这里我实例化了arrayList
//This loop adds a new Line object to the lines array for every line in the file read.
while( reader.hasNext() ) {
for( int i = 0; i < numLines; i++ ) {
int x = reader.nextInt();
int y = reader.nextInt();
Point beg = new Point(x,y);
x = reader.nextInt();
y = reader.nextInt();
Point end = new Point(x,y);
String color = reader.next();
Line l = new Line( beg, end, color );
//----------------
// Change to make sure that you only add lines that don't already exist.
//--------------------
lines.add(l);
//lines[i] = l;
在这里我尝试将“l”行添加到列表中}
}
if( lines != null ) {
for( Line l: lines ) {
int x1 = l.getBeg().getX();
int y1 = l.getBeg().getY();
int x2 = l.getEnd().getX();
int y2 = l.getEnd().getY();
g.setColor(l.color);
g.drawLine(x1, y1, x2, y2);
System.out.println(l);
}
}
//Print the action to the console
System.out.println( "drawing lines" );
}
}