online java compile shows the error like this

56 Views Asked by At
static void isPrime (int n) 
 {      int f;
        for(int i=2;i<=Math.sqrt(n);i++)
        {
            if(n % i == 0)
            {
                f = 1;
            }
        }
        if(n == 1 || f == 1)
        {
            System.out.println("No"); 
        }
        else
         System.out.println("Yes");

 }

Compilation Error

Compilation Error:

prog.java:42: error: variable f might not have been initialized if(n == 1 || f == 1) ^ 1 error

2

There are 2 best solutions below

0
On

In .NET integers and other value types always have default values. So in C# variable 'f' would have the default integer value of 0.

I guess Java is different... To get rid of this compile error, simply assign a value to f.

In example:

int f = 0;
0
On

Just initialize it f to zero.

static void isPrime (int n) {      
    int f=0;

    for(int i=2;i<=Math.sqrt(n);i++){
        if(n % i == 0){
            f = 1;
        }
    }

    if(n == 1 || f == 1){
        System.out.println("No"); 
    }else
        System.out.println("Yes");

 }