【发布时间】:2013-12-08 20:16:14
【问题描述】:
我需要一些关于课堂作业的指导。我目前有一个由红色和蓝色矩形组成的金字塔,我的任务是通过创建各种颜色的数组(准确地说是 9 个)来随机化这些颜色。我在创建数组时遇到了一些麻烦,因为它一直给我一个错误,我希望有人能指出我正确的方向让我开始。这是我的代码:我当前的数组是否正确?我以我教科书中的一个例子为基础建立了这个数组,但它似乎没有用。任何帮助将不胜感激。
@SuppressWarnings("serial")
public class Legos2 extends JFrame {
private int startX;
private int startY;
private int legoWidth;
private int legoHeight;
private int baseLength;
private int arcWidth;
private int arcHeight;
//Declare and Array of Colors
Color[] colors;
//Allocate the size of the array
colors = new Color[4];
//Initialize the values of the array
colors[0] = new Color(Color.red);
colors[1] = new Color(Color.blue);
colors[2] = new Color(Color.yellow);
colors[3] = new Color(Color.green);
// Constructor
public Legos2() {
super("Jimmy's LEGOs");
startX = 20;
startY = 300;
legoWidth = 50;
legoHeight = 20;
baseLength = 10;
arcWidth = 2;
arcHeight = 2;
}
// The drawings in the graphics context
public void paint(Graphics g)
{
// Call the paint method of the JFrame
super.paint(g);
int currentX = startX;
int currentY = startY;
//row = 0 is the bottom row
for (int row = 1; row <= baseLength; row++)
{
currentX = startX;
System.out.println("row = " + row);
for (int col = 0; col <= baseLength - row; col++)
{
if (col % 2 == 0)
g.setColor(Color.red);
else
g.setColor(Color.blue);
System.out.println("col = " + col);
g.fillRoundRect(currentX, currentY, legoWidth, legoHeight, arcWidth, arcHeight);
currentX = currentX + legoWidth;
}
currentY -= legoHeight;
startX += legoWidth /2;
}
}
// The main method
public static void main(String[] args) {
Legos2 app = new Legos2();
// Set the size and the visibility
app.setSize(550, 325);
app.setVisible(true);
// Exit on close is clicked
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
【问题讨论】:
-
“因为它总是给我一个错误”最好显示错误消息和它发生的位置
-
错误发生在我将它们分配给各种颜色的数组中。例如“colors[0] = new Color(Color.red);”错误为“红色”,消息为“红色无法解析或不是字段”。