-1

If I compile this, I get 'cannot find symbol' errors with the distance and ratio variables used inside the while loop. My problem is I don't understand why.

public static void moveSomeSlugs(Point[]slugs, double d, PrintStream output){
    for (int i = 0; i<(slugs.length); i++){
        double distance = Math.sqrt((Math.pow((slugs[(i+1)%4].x-slugs[i].x), 2))+(Math.pow((slugs[(i+1)%4].y-slugs[i].y), 2)));
        double ratio = d/distance;
    }
    while (d < distance){
        for (int i = 0; i<(slugs.length); i++){
            double xmoveDist = (slugs[(i+1)%4].x-slugs[i].x)*ratio;
            double ymoveDist = (slugs[(i+1)%4].y-slugs[i].y)*ratio;
            output.print (slugs[i].x + " " + slugs[i].y + " ");
            slugs[i].x += xmoveDist;
            slugs[i].y += ymoveDist;
            output.println (slugs[i].x + " " + slugs[i].y);
            distance = Math.sqrt((Math.pow((slugs[(i+1)%4].x-slugs[i].x), 2))+(Math.pow((slugs[(i+1)%4].y-slugs[i].y), 2)));
            ratio = d/distance;

2 Answers2

0

You are defining ratio and distance inside the for loop. If you want them accessible from outside of it, you should define them outside of it:

double distance = 0.0;
double ratio = 0.0;
for (int i = 0; i<(slugs.length); i++){
    distance = Math.sqrt((Math.pow((slugs[(i+1)%4].x-slugs[i].x), 2))+(Math.pow((slugs[(i+1)%4].y-slugs[i].y), 2)));
    ratio = d/distance;
}
while (d < distance) {
    // etc...
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • My problem is that I want distance and ratio to use the values from the for loop. There isn't any easy way of doing this is there? – Colin Walker Nov 07 '14 at 16:24
  • You'll still **assigning** them values inside the `for` loop - you're just **defining** them in a broader scope. – Mureinik Nov 07 '14 at 16:28
0

Your variable distance is declared inside the for loop. That's why your while loop cannot access it. What you can do is declare the variable outside the loop:

 double distance = 0; 
 double ratio = 0;

 for (int i = 0; i<(slugs.length); i++){
    distance = Math.sqrt((Math.pow((slugs[(i+1)%4].x-slugs[i].x), 2))+(Math.pow((slugs[(i+1)%4].y-slugs[i].y), 2)));
    ratio = d/distance;
 }
 while (d < distance){
GameDroids
  • 5,584
  • 6
  • 40
  • 59