我看了很多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