gpt4 book ai didi

java - 如何防止我的变量永远持续下去?

转载 作者:行者123 更新时间:2023-12-01 14:47:58 25 4
gpt4 key购买 nike

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

}}

最佳答案

我觉得应该是

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 循环中,循环变量 x1y1 永远不会更改,这意味着它们始终为 01 将永远满足条件,这就是你的程序永远运行的原因。

在任何带有临时变量的循环中,您需要更改循环变量的值,以便在某个阶段满足条件。

在这里,我们将在循环内递增 x1y1 变量,并且 x1 循环中的 retuen 语句将导致循环退出第一次执行后,必须将其删除。

此外,您始终获得像素 (x,y),x 和 y 的值在整个循环中保持不变,我猜您这里需要的是像素 (x1, y1)

关于java - 如何防止我的变量永远持续下去?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15215001/

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