Question

When using my code I am receiving an output message stating that each number that I have entered is prime, even if it is not a prime number. How can I change my output message to reflect the correct is or is not prime result? Here is my code:

public static void main (String [] args){
//prompt user to input a number

String input = JOptionPane.showInputDialog("Enter number "); 
// change string to int
    int number = Integer.parseInt(input); 

//display message to user of their results
    BigInteger num = new BigInteger(input); 

    String output = number + " is" + (BigInteger(input) ? " " : " not ") + "a prime     number: " + BigInteger(input);

        JOptionPane.showMessageDialog (null, output);

}

public static Boolean IsPrime(BigInteger num) {
// check if number is a multiple of 2
if (num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
  return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(num) <= 0; i =
    i.add(new BigInteger("2"))) {
  if (num.mod(i).compareTo(BigInteger.ZERO) == 0) {

   return false;
  }
}
return true;

}

Was it helpful?

Solution

I think you're having an issue here -

String output = number + " is" 
    + (BigInteger(input) ? " " : " not ") + "a prime     number: " 
    + BigInteger(input);

And you want something more like this -

String output = num + " is" 
    + (IsPrime(num) ? " " : " not ") + "a prime number.";

I tested your IsPrime function, and it correctly identified 5 as prime and 4 as not prime. You should probably rename it isPrime to be inline with Java naming conventions.

EDIT

public static void main(String[] args) {
    // prompt user to input a number

    String input = JOptionPane.showInputDialog("Enter number ");
    // change string to int
    int number = Integer.parseInt(input);

    // display message to user of their results
    BigInteger num = new BigInteger(input);

    String output = num + " is" + (IsPrime(num) ? " " : " not ")
            + "a prime number.";

    JOptionPane.showMessageDialog(null, output);
}

First prompt

Not Prime

Is Prime

OTHER TIPS

I guess you simply was wrong in the main code; try with this one;

public static void main (String [] args){
        //prompt user to input a number

        String input = JOptionPane.showInputDialog("Enter number "); 
        // change string to int
        int number = Integer.parseInt(input); 

        //display message to user of their results
        BigInteger num = new BigInteger(input); 

        String output = number + " is" + (IsPrime(num) ? " " : " not ") + "a prime number: " + number;

        JOptionPane.showMessageDialog (null, output);
    }

Angelo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top