-2
我寫了一些代碼,它在for循環中逐行讀取文本文件;每行是用於在JPanel上繪製新形狀的命令。 我有一個HashMap用於存儲名稱和形狀。在將新對象放入HashMap時陷入無限循環
Map<String, GeoShape> geoObj = new HashMap<String, GeoShape>();
樣品輸入是這樣的: ADD P1點藍50 50 10
cmd是一個String []保持分裂輸入命令。 ,問題就在這裏:
if (cmd[2].equalsIgnoreCase("Point"))
geoObj.put(cmd[1], new Point(cmd, graph));
它屬於無限循環。我在調試模式下運行代碼,類Point沒有任何問題。
任何幫助,非常感謝!
編輯:這是階級觀點
public class Point extends Segment {
private Line2D point;
private Stroke thickness;
private Color fColor;
private double x;
private double y;
public Point(String[] cmd, Graphics2D graph) {
System.out.println("point");
x = Double.parseDouble(cmd[4]);
y = Double.parseDouble(cmd[5]);
try {
fColor = setColor(cmd[3]);
} catch (Exception e) {
e.printStackTrace();
}
thickness = new BasicStroke(Integer.parseInt(cmd[6]));
paint(graph);
}
@Override
public void paint(Graphics2D graph) {
point = new Line2D.Double(x, y, x, y);
graph.setStroke(thickness);
graph.setColor(fColor);
graph.draw(point);
}
}
for循環:
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int linesNum = Integer.parseInt(br.readLine());
String line = br.readLine();
for (int i = 1; i <= linesNum; i++) {
while (line != null) {
cmd = line.split(" ");
if (cmd[0].equalsIgnoreCase("ADD")) {
if (cmd[2].equalsIgnoreCase("Point"))
geoObj.put(cmd[1], new Point(cmd, graph));
// some else if with the same structure for other shapes
//at the end of for loop I have this: line = br.readLine();
有沒有幫助這個問題。你沒有提供任何可以給任何人提供線索的數據。如果你在調試模式下運行,你應該有你需要的所有信息。 Point或您寫的其他課程有問題。 Map或HashMap沒有問題。我的猜測是一個糟糕的點構造函數。 – duffymo 2013-04-20 17:43:03
檢查for循環,什麼是中斷條件? – NINCOMPOOP 2013-04-20 17:44:18
'readLine()'應該在流結束時返回null。 readline不會在每次迭代中調用,或者流不會結束。 [來源](http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedReader.html#readLine()) – user000001 2013-04-20 18:30:00