Dr.Java将不会运行我的程序,因为我的变量将永远存在,我不知道如何防止这种情况发生。如果你能告诉我如何解决这个问题,那就太好了。我是初学者,所以这对我来说都很陌生。
这是该类的代码:
import java.awt.Color;
class PaintablePicture extends Picture {
public PaintablePicture(String fileName) {
super(fileName);
}
public void purpleSplotch(int x, int y) {
int x1 = 0;
int y1 = 1;
while (x1 < x * 2)
while (y1 < y * 3)
{
Color purple = new Color(175, 0, 175);
Pixel pixRef;
pixRef = this.getPixel(x, y);
pixRef.setColor(purple);
}
return;
}
}
然后这是我正在运行它的方法(忽略所有其他类的艺术乌龟的东西,一切正常,直到我开始绘制可绘画的图片。
public class GraffitiApp
{
public static void main(String[] a)
{
FileChooser.pickMediaPath();
PaintablePicture pRef;
pRef = new PaintablePicture(FileChooser.pickAFile());
pRef.purpleSplotch(14,14);
pRef.purpleSplotch(17,20);
ArtisticTurtle tRef = new ArtisticTurtle(pRef);
tRef.pentagon(20);
tRef.spiral(50);
tRef.penUp();
tRef.forward(-50);
tRef.turn(90);
tRef.penDown();
tRef.letterK(50);
tRef.penUp();
tRef.turn(-130);
tRef.forward(100);
tRef.turn(90);
tRef.forward(140);
tRef.penDown();
tRef.letterK(30);
tRef.penUp();
tRef.moveTo(486, 60);
tRef.penDown();
tRef.star(30);
tRef.penUp();
tRef.moveTo(159,122);
tRef.turn(30);
tRef.penDown();
tRef.star(60);
tRef.penUp();
tRef.moveTo(330,103);
tRef.turn(-67);
tRef.penDown();
tRef.pentagon(40);
tRef.penUp();
tRef.moveTo(471,158);
tRef.penDown();
tRef.spiral(35);
pRef.explore();
} }
答案 0 :(得分:1)
我认为应该是
class PaintablePicture extends Picture {
public PaintablePicture(String fileName) {
super(fileName);
}
public void purpleSplotch(int x, int y) {
int x1 = 0;
int y1 = 1;
while (x1 < x * 2)
while (y1 < y * 3)
{
Color purple = new Color(175, 0, 175);
Pixel pixRef;
// get pixels (x1, y1) instead of (x, y) there is use to set the color of the same pixel(x,y) in a loop
pixRef = this.getPixel(x1, y1);
pixRef.setColor(purple);
// increment y1
y1++;
}
// increment x1
x1++;
}
}
在你的while循环中,循环变量x1
和y1
永远不会改变,这意味着它们始终是0
和1
,它将永远满足条件,即为什么你的程序永远在运行。
在任何带有temp变量的循环中,您需要更改循环变量的值,以便在某个阶段满足条件。
这里我们将增加其循环中的x1
和y1
变量,x1
循环中的retuen语句将导致循环在第一次执行后退出,它必须是除去。
你总是得到像素(x,y),x和y的值在整个循环中保持不变,我猜你需要的是pixles(x1,y1)
答案 1 :(得分:0)
您的问题是您没有在while
循环中递增用作索引的变量,因此循环无限期地运行。增加两个变量(x1
和y1
)以确保在某个时刻退出while循环。目前,x1
永远不会超过x
而y1
永远不会超过y
。
while(x1 < x*2) {
while(y1 < y*3) {
Color purple = new Color(175, 0, 175);
Pixel pixRef;
pixRef= this.getPixel(x,y);
pixRef.setColor(purple);
//increment y1 here
y1++;
}
//increment x1 here
x1++;
}
答案 2 :(得分:0)
当然会永远运行
while(x1 < x*2)
在调用方法
时,x的值大于0pRef.purpleSplotch(14,14);
y1的while循环也是如此。
您可能需要在purpleSplotch方法中增加x1和y1。我不知道它必须做什么,但条件总是如此,因此无限循环。