我看了很多for循環的例子,我無法弄清楚爲什麼我的工作不起作用。在我的程序中有一個組件,查看器和一個建築類。我設置了它,當你在組件中創建一個新的建築物時,你輸入x-pos,y-pos和#層。我想運行for循環來創建每個級別,但它不會工作。請幫助和謝謝。For循環將不起作用
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Building
{
/**number of levels the building has*/
private int levels;
private int xLeft;
private int yTop;
private int lvls;
/**
* Constructor for objects of class Building
*
* @param x x-Coordinate
*
* @param y y-Coordinate
*
* @param levels The number of thevels the building will have
*/
public Building(int x, int y, int lvls)
{
xLeft = x;
yTop = y;
levels = lvls;
}
/**
* Draws the building
*
* @param g2 graphics contex
*/
public void draw(Graphics2D g2)
{
/**creates one building level*/
Rectangle body = new Rectangle(xLeft/*X*/, yTop/*Y*/, 100/*Width*/, 100/*Height*/);
/**creates window inside of building level*/
Rectangle window = new Rectangle(xLeft+25, yTop+25, 50, 50);
g2.setColor(Color.DARK_GRAY);
g2.fill(body);
g2.setColor(Color.ORANGE);
g2.fill(window);
/**Creates (levels) number of levels*/
for(int i = 1; i<=levels; i++)
{
/**Adds 100 to y value of body*/
body.setLocation(xLeft, yTop-100);
g2.setColor(Color.DARK_GRAY);
g2.fill(body);
window.setLocation(xLeft+25, yTop-75);
g2.setColor(Color.ORANGE);
g2.fill(window);
}
}
}
您是否嘗試過調試?你將哪個值傳遞給'levels'成員? – Mephy 2014-10-19 03:04:10
你正在努力成爲一名程序員,所以你需要更具體地瞭解你的狀況。你是什麼意思,它不起作用?!!! 1 – 2014-10-19 03:21:35
由於它不起作用,我的意思是循環內沒有任何執行的語句。我試着把一個System.out.println(「測試」);在其中,並沒有打印,所以循環沒有運行。 – twoface1997 2014-10-19 03:31:28