我需要帮助解决一些代码问题。我正在学习我的第一个java课程,所以它非常基础。基本上,我需要使用switch语句绘制一系列3个房屋,但每个房屋绘制在不同的位置并且具有不同的墙壁颜色。下面是我一直在玩的代码。
public class Neighborhood extends Applet {
public void paint (Graphics page) {
int xOffset = 50;
int yOffset = 0;
Color houseColor = Color.yellow;
switch (houseColor) {
case 0: houseColor = Color.red;
case 1: houseColor = Color.blue;
case 2: houseColor = Color.green;
Polygon poly = new Polygon(); // Roof Polygon
poly.addPoint (50,90);
poly.addPoint (150, 50);
poly.addPoint (250, 90);
page.setColor (new Color(218,165,32)); // Custom brown color
page.fillPolygon (poly);
page.setColor (Color.black);
page.drawLine (50, 90, 150, 50); // Roof outline
page.drawLine (150, 50, 250, 90);
page.setColor (Color.green);
page.fillRect (50, 90, 200, 100); // House base with houseColor
page.setColor (Color.black);
page.drawRect (50, 90, 200, 100); // House outline
page.setColor (Color.black);
page.fillRect (75, 110, 30, 25); // Window 1
page.fillRect (190, 110, 30, 25); // Window 2
page.setColor (Color.white);
page.drawLine (75, 123, 105, 123); // Window Frame 1
page.drawLine (89, 110, 89, 134);
page.fillRect (70, 110, 5, 25); // Shutter 1
page.fillRect (105, 110, 5, 25); // Shutter 2
page.drawLine (75+115, 123, 105+115, 123); // Window Frame 2
page.drawLine (89+115, 110, 89+115, 134);
page.fillRect (70+115, 110, 5, 25); // Shutter 3
page.fillRect (105+115, 110, 5, 25); // Shutter 4
page.setColor (Color.red);
page.fillRect (130, 150, 35, 40); // Door
page.setColor (Color.blue);
page.fillOval (155, 170, 4, 4); // Door knob
}
}}
它相当直接,我不需要它进行交互或做任何疯狂的事情。我已经改变了这个代码大约一百万次试图让它工作,但我已经意识到它是时候让更好的眼睛去看看。任何帮助表示赞赏。感谢。
答案 0 :(得分:0)
首先,你忘记了休息陈述。
switch (houseColor) {
case 0: houseColor = Color.red; break;
case 1: houseColor = Color.blue; break;
case 2: houseColor = Color.green; break;
如果你没有休息时间,它将进入下一个声明。此外,您没有使用颜色。这是故意的吗?
如果你想画3个房子,可以这样做:
private void drawHouses() {
// make an array of colors
Color[] colors = new Color[] { Color.RED, Color.BLUE, Color.GREEN };
// loop through the colors
for(int i = 0 ; i < colors.length; i ++ ) {
// use the index of the loop for the position of the house and for the current color.
drawHouse(i * 50, 100, colors[i]);
}
}
private void drawHouse(int x, int y, Color color) {
// draw house here
}
此外,目前您正在使用硬编码值。没关系,但你需要分别将x和y参数添加到x和y轴。例如,如果你想绘制一个100,150,50乘50的正方形,你需要增加100 x(100 + x)和150 x(150 + y)