Monday, July 27, 2009

Why doesn't my program print the number of primes???

class ReturnNumberOfPrimes


{


public static void main (String args [])


{


int c[ ]={12,13,7, 2, 5};


int a=ReturnNumberOfPrimes(c);


System.out.print(a);


}





public static int ReturnNumberOfPrimes (int list [ ])


{


for (int i=0; i%26lt;list.length; i++)


{


if(list[i]%2!=0 %26amp;%26amp; list[i]%3!=0)


}


return i;


}


}

Why doesn't my program print the number of primes???
The piece of code does not even compile. There are a few problems in your code:





1. You may consider putting a block of code in your if statement.





if(list[i]%2!=0 %26amp;%26amp; list[i]%3!=0) {


// do something


}





2. The variable "i" is out of scope because it was defined in the for loop. Any reference outside the for loop would be considered as illegal by the compiler.





A suggested solution could be:





public static int ReturnNumberOfPrimes (int list [ ])


{


int conuter = 0;


for (int i=0; i%26lt;list.length; i++)


{


if(list[i]%2!=0 %26amp;%26amp; list[i]%3!=0) {


counter++;


}


}


return counter;


}


}





Good luck!


No comments:

Post a Comment