 CheeseHacker -4 years ago 88
Java Question

# Trying to write code that asks the user for a number, determines if it's prime, and lists the prime numbers between one and that number

For some reason when I test this, the second if statement always prints every number between one and the number the user input as not prime, even if it is. However, the third if statement correctly states if the user's number is prime or not. Is there something wrong that I am doing?

``````public static void main(String[] args) {

@SuppressWarnings("resource")
Scanner input = new Scanner(System.in) ;

System.out.println("intput a number") ;
int number = input.nextInt() ;

int counter = 0 ;
int counter2 = 0 ;

for (int i = 1 ; i <= number ; i++) {
for (int j = 1 ; j <= i ; j++) {
if (i % j == 0 ) {
counter ++ ;
}
else if (i%j != 0) {
}
}
if (counter != 2) {
System.out.println( i+" is not prime") ;
}
if (counter == 2) {
System.out.println(i+", is a prime") ;
}
System.out.println("\n") ;
if (number % i == 0) {
counter2 ++ ;
}
}
if (counter2 != 2) {
System.out.println( number+" is not prime") ;
}
else if (counter2 == 2){
System.out.println( number+" is a prime") ;
}
}
`````` Sacha

You are using the same counter for all the numbers but you are not reseting it, so the counter's value is going up and up.

``````int counter;
int counter2 = 0 ;

for (int i = 1 ; i <= number ; i++) {

//Resets the counter
counter = 0 ;

for (int j = 1 ; j <= i ; j++) {
if (i % j == 0 ) {
counter ++ ;
}
else if (i%j != 0) {
}
}

//You don't need two if's if one is the negation of the other
if (counter != 2) {
System.out.println( i+" is not prime") ;
}
else{
System.out.println(i+", is a prime") ;
}
System.out.println("\n") ;
if (number % i == 0) {
counter2 ++ ;
}
}
//You don't need two if's if one is the negation of the other
if (counter2 != 2) {
System.out.println( number+" is not prime") ;
}
else{
System.out.println( number+" is a prime") ;
}
``````

Also you could avoid headaches if you made an isPrime function to tell you if the numbers are prime or not, it would look cleaner.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download