我很困惑如何使用數組列表和對象。我已經創建了對象,並可以將它們添加到我的泛型類的數組列表中。但老師要我們讀一個文本文件,如本如何將對象存儲在通用類中按名稱排列列表和參考Java - 作業
start picture A
circle 0 100 20
rectangle 100 100 20 30
end picture
draw picture A blue 10 10
我不知道如何處理或參考的對象,一旦我把它們裝入數組列表。 基本上我不明白的泛型類圖片。這裏有一個指向任務的鏈接。任何明確我需要在我的圖片類來調用和操作對象將不勝感激。
http://www.cs.csustan.edu/~mthomas/cs3100/cs3100_hwk1.html
import java.awt.Graphics;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class TestCircle {
private static String fileName;
private static String line;
public static void main(String[] args) {
try {
readLines();
} catch (Exception e) {
e.printStackTrace();
}
}
static void readLines() throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the file name ---> ");
fileName = input.next();
FileReader fr = new FileReader(fileName);
BufferedReader inFile = new BufferedReader(fr);
// loop through lines
while ((line = inFile.readLine()) != null) {
System.out.println(line);
txtAnalysis(line);
}
// close file
inFile.close();
}
public static void txtAnalysis(String line) {
DrawingPanel panel = new DrawingPanel(600, 600);
Graphics g = panel.getGraphics();
Picture<Shape> pictures = new Picture<Shape>("All Pictures");
if (line.startsWith("start picture")) {
String name = line.split(" ")[2];
pictures.setName(name);
System.out.println("start");
}
if (line.startsWith("circle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
Circle c1 = new Circle("circ", x, y, z); // small and upper left
// c1.draw(g, 0, 0);
// c1.dance(g, 0, 0, 600, 600);
pictures.add(c1);
System.out.println("circle");
}
if (line.startsWith("rectangle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
System.out.println("rectangle");
Rectangle r1 = new Rectangle("circ", x, y, z);
// r1.draw(g, 0, 0);
// r1.dance(g, 0, 0, 600, 600);
pictures.add(r1);
System.out.println("rectangle");
}
if (line.startsWith("end picture")) {
line = null;
}
else {
System.out.println("end of loop");
}
}
}
,這就是我在Picture類爲止。
import java.util.*;
class Picture <E extends Shape> {
private ArrayList<Shape> pictures;
private String name;
public Picture(String n) {
name = n;
pictures = new ArrayList<Shape>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean add(E newA) {
boolean b = pictures.add(newA);
return b;
}
}
這是一個完全合法的問題,你認爲這是作業,並顯示你到目前爲止的嘗試。誰低估了你是無用的 - 特別是因爲他或她沒有膽量來解釋爲什麼。 – Vidya