# Method returning boolean

• November 13th, 2010, 04:46 PM
Plural
Method returning boolean
Assignment:
isPrime Method
A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly 1, 2, 3, and 6.
Write a method named isPrime, which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. Demonstrate the method in a complete program.

Code java:

```package isprimemethod; import javax.swing.JOptionPane;   /** * * @author uuuuuuu */ public class Main {   /** * @param args the command line arguments */ public static void main(String[] args) { String input; int num; boolean bool;   input = JOptionPane.showInputDialog("Enter an integer."); num = Integer.parseInt(input);   bool = isPrime(num); System.out.println(bool);   }   public static boolean isPrime(int num) { boolean bool; { if(num%1==0 && num%num==0) bool = true; else bool = false; } return bool; } }```

I tried a few numbers out but the outcome is always "true". No outcome came out to be "false".
What is wrong with the code?
• November 13th, 2010, 05:04 PM
javapenguin
Re: Method returning boolean
if(num%1==0 && num%num==0)

num%1 means the remainder of num/1 which is 0.

num/num = 1 with remainder 0.

Always true unless perhaps num = 0;
• November 13th, 2010, 05:28 PM
Plural
Re: Method returning boolean
Quote:

Originally Posted by javapenguin
if(num%1==0 && num%num==0)

num%1 means the remainder of num/1 which is 0.

num/num = 1 with remainder 0.

Always true unless perhaps num = 0;

I know that but, what part of the code do I change in order for it to make certain values to become "false" which is supposed to be false, whereas "true" is true.
• November 13th, 2010, 05:45 PM
javapenguin
Re: Method returning boolean
Ohhhh, non-prime numbers also would have that factor.

Have a for loop that starts at 3

Code java:

```public static boolean isPrime(int num) {   if (num <=1) return false;   // if num = 2, it will skip the for loop and return true.   // but if for some reason it doesn't, then just change it to x = 3 and have condition // if (num==2) return true;   for (int x =2; x < num; x++) { if (num%x ==0) return false;   } return true;   }```