Prime Number Program for class

idea here is to have user input an int n and find the prime numbers between 2 and n. then print out how many prime numbers there are for example.. 2-100 = 25 prime numbers. i cant figure out whats wrong with this so far. somehow i get high numbers when i run this program. help pls? :D.

Code Java:

public class Prime
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n;
String choice;
do
{
System.out.print("Enter in value for n: ");
n = scanner.nextInt();
int primes = 0;
for(int i=3; i<=n; i++)
{
for(int j=2; j<i; j++)
{
if(i%j == 0){}
else{
primes = primes +1;}
}
}
System.out.println("Number of primes: " +primes);
System.out.println("Do you want to continue? Y/N: ");
choice = scanner.next();
}while (choice.equalsIgnoreCase("Y"));
}
}

Re: Prime Number Program for class

You're increasing the prime count whenever a number in question isn't divisible by another number, but you're suppose to only increase the count when the number in question isn't divisible by all other numbers greater than 1 and less than itself (subtle difference here).

Re: Prime Number Program for class

how could i implement that into my code? should i put another if in there??

Re: Prime Number Program for class

Adding/removing code willy nilly without understanding what's going on is not a good debugging technique. Examine what your algorithm for checking if a number is prime is actually doing (i.e. work it out as if you were the computer). Try it out with the number 5 (which is prime), as well as with the number 6 (which is not prime). Pay attention to when the prime count increases, then see if you can't figure out a better way to check for what I suggested earlier (hint: you'll probably end up needing another if statement and a boolean flag).

Re: Prime Number Program for class

we haven't learned boolean flag. but ill try to do what you said.

Re: Prime Number Program for class

You haven't learned about booleans yet? Hmm, that seems kind of odd. Booleans are values which can either be true or false.

Code Java:

boolean isPrime = false; // a boolean variable is set to false
if(isPrime) // equivalent to if(isPrime == true)
{
System.out.println("this will never execute");
}

Without booleans, you'd need to use breaks and instead of keeping track of how many numbers are prime, you'd need to keep track of how many numbers are composite. Once you've figured out how many composite numbers there are, you know that the rest of the numbers are prime.

Re: Prime Number Program for class

yah haven't learned booleans yet but learned about breaks, and ill try to get the composite then. thanks for the help.