嗨我想知道是否有可能获得数组元素的长度?我检查了java文档,我看到的唯一可检索的长度是数组本身的长度。我的任务是使用元素的长度随机化我的砖块的颜色。如果有人可以指出获得元素长度的正确方向,那将非常感激。这是我的代码:
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
@SuppressWarnings("serial")
public class legos2v2 extends JFrame {
private int startX;
private int startY;
private int legoWidth;
private int legoHeight;
private int baseLength;
private int arcWidth;
private int arcHeight;
private Color[] colors;
// Constructor
public legos2v2() {
super("Jimmy's LEGOs");
startX = 20;
startY = 300;
legoWidth = 50;
legoHeight = 20;
baseLength = 10;
arcWidth = 2;
arcHeight = 2;
// Declare and Array of Colors
Color[] colors = {Color.red, Color.blue, Color.yellow, Color.green,
Color.pink, Color.black, Color.magenta, Color.orange,
Color.cyan};
// Get length of color
System.out.println("Array Length = " + colors.length + "\n");
}
// The drawings in the graphics context
public void paintComponent(Graphics g) {
// Call the paint method of the JFrame
super.paint(g);
int currentX = startX;
int currentY = startY;
Random random = new Random();
// row = 0 is the bottom row
for (int row = 1; row <= baseLength; row++) {
currentX = startX;
for (int col = 0; col <= baseLength - row; col++) {
g.fillRoundRect(currentX, currentY, legoWidth, legoHeight, arcWidth, arcHeight);
// Generate random integer from 0 to 8
int randomIndex = random.nextInt(colors.length);
g.setColor(this.colors[randomIndex]);
//Error here this.colors = colors[randomIndex];
// Print random integers to screen
System.out.println(randomIndex);
currentX = currentX + legoWidth;
}
currentY -= legoHeight;
startX += legoWidth / 2;
}
}
// The main method
public static void main(String[] args) {
legos2v2 app = new legos2v2();
// Set the size and the visibility
app.setSize(550, 325);
app.setVisible(true);
// Exit on close is clicked
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:2)
老师要求你做的是我在评论中所说的:
初始化颜色数组:
Color[] colors = ...;
在0(包含)和数组长度之间生成一个随机int(不包括:
int randomIndex = random.nextInt(colors.length);
返回一个整数,它是颜色数组的有效索引。
选择随机索引处的颜色:
Color color = colors[randomIndex];
这避免了丑陋的if
块链产生随机颜色的需要。
编辑:
Color[] colors =
替换为this.colors =
以初始化实例变量,而不是重新定义具有相同名称的本地变量Random random = new Random();
paintComponent()
而不是覆盖paint()
。