java中的变量未在循环中保存其值
我迭代一个圆(r)的可能半径,当我找到潜在的候选点时,我基本上想把它们推到堆栈上。我只需要记住最后两个半径和它们对应的圆的颜色,所以我创建了四个整数来存储这些变量。但是,我包含的print语句总是为这两个变量生成0的值java中的变量未在循环中保存其值,java,variables,loops,scope,Java,Variables,Loops,Scope,我迭代一个圆(r)的可能半径,当我找到潜在的候选点时,我基本上想把它们推到堆栈上。我只需要记住最后两个半径和它们对应的圆的颜色,所以我创建了四个整数来存储这些变量。但是,我包含的print语句总是为这两个变量生成0的值 //small stack to hold values of previous circles int small_radius = 0; int small_color = 0;
//small stack to hold values of previous circles
int small_radius = 0;
int small_color = 0;
int med_radius = 0;
int med_color = 0;
//iterate through possible radii
while (r<max){
//check for possibility of a circle
if(detectCircle(x,y,r,img,g)){
//confirm it is a circle and store its color
int large_color = confirmCircle(x,y,r,img,g);
if(large_color != -1){
//if it is a circle, compare the medium circle against the current one and the small one
//check if the current circle and small circle do not immediately surround the medium circle
boolean matches_small = (med_radius-1 == small_radius && med_color == small_color);
boolean matches_large = (r-1 == med_radius && large_color == med_color);
if(!matches_small && !matches_large){
//if it is a circle of single line thickness, draw it
System.out.println("med_radius: "+med_radius+" small_radius: "+small_radius);
drawCircle(x,y,r,img,g);
}
//now push the current circle onto the stack.
small_radius = med_radius;
small_color = med_color;
med_radius = r;
med_color = large_color;
}
}
r++;
}
//用于保存上一个圆的值的小堆栈
int小半径=0;
int small_color=0;
int med_半径=0;
int med_color=0;
//迭代可能的半径
而(r此示例中没有分配给四个变量中任何一个的代码
如果您是在confirmCircle()
中执行赋值,那么问题是您希望int
s在Java中按值传递时按引用传递
换言之:
int a = 4;
public void changeA(int someVar) {
someVar++;
}
changeA(a);
System.out.println(a); //prints 4, not 5.
调试器指向什么?您是否尝试过使用它?如果没有confirmCircle
的代码,就无法知道是什么问题。如果每次返回-1,您将得到您看到的结果。我们需要更多信息以提供有意义的帮助。您的println语句在指定med_radius之前。是否应在g r显示med_radius?因为med_radius等于r.@JonathanDrapeau,如果它返回-1,则不会调用print语句。奇怪..我刚刚测试了你的代码(max=10,伪造方法只返回将进入循环的值,并强制布尔值为false,以保证打印)打印出来的所有内容都会像应该的那样递增…confirmCircle()返回圆的RGB值,然后我将其分配给这个循环中的一个变量。
int a = 4;
public void changeA(int someVar) {
someVar++;
}
changeA(a);
System.out.println(a); //prints 4, not 5.