Search code examples
javadeclare

variable cannot be resolved to variable inside loop


I've written the following Java in attempt to find primes less than 1000:

public class primes {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("2"); 
        int n=2;
        While (n<1000);
        {
            for(int d = 2; d<n; d++); //if d|n abort divisors loop and try next number
            {

                if (n%d == 0){ //if d|n try next number
                    n++;
                    break;
                }

                if (d>(n/2)){ //if there are no divisors up to n/2 n is prime, print n then try next number
                    System.out.println(n);
                    n++;
                    break;
                }
                d++; //try next divisor

            }           
        }
    }
    private static void While(boolean b) {
        // TODO Auto-generated method stub  
    }
}

I get bugs each time d is called in the inner loop that it is not declared as a variable. But I declared in in the for statement. I've read several examples where you can do this. What's wrong here, and how to resolve?


Solution

  • Here is your corrected code (contained in main(String[] args), not in a class):

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("2"); 
        int n=2;
        while (n<1000)
        {
            for(int d = 2; d<n; d++) //if d|n abort divisors loop and try next number
            {
    
                if (n%d == 0){ //if d|n try next number
                    break;
                }
    
                if (d>(n/2)){ 
                    //if there are no divisors up to n/2 n is prime, print n
                    //then try next number
                    System.out.println(n);
                    n++;
                    break;
                }
    
            }  
            n++;
        }
    }
    

    However, you need to learn (or relearn) the language. You stumped me for a few minutes with your SEMICOLONS after the while and for loops. I also discovered many more errors with the code. I believe that you can code well, but you need to learn the basics of Java first.