gpt4 book ai didi

java - 返回数组元素的长度

转载 作者:行者123 更新时间:2023-12-02 06:29:33 25 4
gpt4 key购买 nike

嗨,我想知道是否可以获取数组元素的长度?我查看了 java 文档,我看到的唯一可检索的长度是数组本身的长度。我的任务是使用元素的长度来随机化我的砖 block 的颜色。如果有人能够指出获取元素长度的正确方向,我们将不胜感激。这是我的代码:

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);
}
}

最佳答案

老师要求你做的就是我在评论中说的:

  1. 初始化颜色数组:

    Color[] colors = ...;
  2. 生成一个介于 0(含)和数组长度(不含:)之间的随机整数

    int randomIndex = random.nextInt(colors.length);

    这将返回一个整数,它是颜色数组的有效索引。

  3. 在随机索引处选择颜色:

     Color color = colors[randomIndex];

这避免了使用丑陋的 if block 链来生成随机颜色。

编辑:

  1. Color[] colors = 替换为 this.colors = 以初始化实例变量,而不是重新定义同名的局部变量
  2. 正如其他评论中告诉您的那样,将 Random random = new Random(); 移到第一个 for 循环之前
  3. 正如其他注释中告诉您的那样,重写 paintComponent() 而不是重写 paint()

关于java - 返回数组元素的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20194687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com