我目前正在使用我的AP Java Coding类,我遇到了一个棘手的问题。
我正在尝试使用GObjects / GOval在图形窗口中创建100个具有各种半径的随机圆圈和随机颜色。我试图找出问题并且我确定在for-loop和GOval(circle)创建之间进行通信。我也试过从头开始几次重做这段代码,但我一直遇到同样的问题。特别是我的问题是我的图形窗口只显示一个随机圆而不是100.请,请帮忙。我的代码如下:
请注意,我选择变量c来随机指定颜色。没有押韵或理由,我只需要使用随机值。
import java.awt.Color;
import acm.graphics.GOval;
import acm.program.GraphicsProgram;
import acm.util.RandomGenerator;
public class _100_Random_Circles extends GraphicsProgram
{
public _100_Random_Circles()
{
// Random Number Generator
RandomGenerator rgen = new RandomGenerator();
// Random X-coordinate.
int x = rgen.nextInt(1, 500);
// Random Y-coordinate.
int y = rgen.nextInt(1, 500);
// Random Circle width
int c = rgen.nextInt(1, 100);
// Random Circle height
int d = rgen.nextInt(1, 100);
for(int i = 0; i < 100; i++)
{
GOval circle = new GOval (x, y, c, d);
add(circle);
//Color the circles randomly
if(c <= 10)
{
circle.setFilled(true);
circle.setColor(Color.BLUE);
}
else if(c <= 20)
{
circle.setFilled(true);
circle.setColor(Color.RED);
}
else if(c <= 30)
{
circle.setFilled(true);
circle.setColor(Color.YELLOW);
}
else if(c <= 40)
{
circle.setFilled(true);
circle.setColor(Color.GREEN);
}
else if(c <= 50)
{
circle.setFilled(true);
circle.setColor(Color.ORANGE);
}
else if(c <= 60)
{
circle.setFilled(true);
circle.setColor(Color.BLACK);
}
else if(c <= 70)
{
circle.setFilled(true);
circle.setColor(Color.GRAY);
}
else if(c <= 80)
{
circle.setFilled(true);
circle.setColor(Color.PINK);
}
else if(c <= 90)
{
circle.setFilled(true);
circle.setColor(Color.MAGENTA);
}
else
{
circle.setFilled(true);
circle.setColor(Color.WHITE);
}
}
}
}
答案 0 :(得分:0)
// Random X-coordinate.
int x = rgen.nextInt(1, 500);
// Random Y-coordinate.
int y = rgen.nextInt(1, 500);
// Random Circle width
int c = rgen.nextInt(1, 100);
// Random Circle height
int d = rgen.nextInt(1, 100);
此代码不在您的循环中。你在同一个地方画了100个圆圈。
答案 1 :(得分:0)
正如我在评论中首先指出的那样。
那是因为你的xycd定义在循环之外。那么你只有一个所有圈子的值