简体   繁体   中英

prime numbers switch in a java program has unexpected output

I'm trying to create a program that reads a list of 10 integers and asks the user whether they'd like to know if the integers entered are even/odd, prime, or their sign. I don't see where the mistake is:

import java.io.*;
public class Menu1 {
public static void main(String args[])throws IOException{
    BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
    int array[]=new int[10];
    int a=0, i=0;
    System.out.println("Welcome, please enter 10 integers:");
    try{
        for(i=0;i<10;i++){
            System.out.println("Enter integer "+(i+1)+":");
            array[i]=Integer.parseInt(b.readLine());
        }
    }catch(NumberFormatException e){
        System.err.println("Not an integer! "+e.getMessage());
    }           
    System.out.println("What would you like to know?\n(1) Even/Odd\n(2) Primes\n(3) Sign");
    try{
        a=Integer.parseInt(b.readLine());   
    }catch(NumberFormatException e){
        System.err.println("Not an integer! "+e.getMessage());
    }       
    switch (a){
    case 1:
        for(i=0;i<10;i++){
            if(array[i]%2==0)
                System.out.println(array[i]+" is even");
            else
                System.out.println(array[i]+" is odd");
        }
        break;
    case 2:
        for(int j=0;j<10;j++){
            for(i=2;i<array[j];i++){
                if(array[j]%i==0)
                    System.out.println(array[j]+" isn't prime");
                else
                    System.out.println(array[j]+" is prime");
            }
        }
        break;
    case 3:
        for(i=0;i<10;i++){
            if(array[i]>0)
                System.out.println(array[i]+" is positive");
            else if(array[i]<0)
                System.out.println(array[i]+" is negative");
            else
                System.out.println(array[i]+" has no sign");
        }
        break;
    default:
        System.out.println("Invalid Option");
    }
}

}

case 1 and case 3 work just fine, case 2 is where the strange output occurs; any help will be greatly appreciated

In your code for case 2:

case 2:
    for(int j=0;j<10;j++){
        for(i=2;i<array[j];i++){
            if(array[j]%i==0)
                System.out.println(array[j]+" isn't prime");
            else
                System.out.println(array[j]+" is prime");
        }
    }
    break;

you have put a System.out.println() statement that will execute for every iteration of the for loop. So, if a given element in your array, array , is 5, your code will print out whether or not your number is divisible by every number from 2 to 5. This probably isn't what you want.

To fix this, there are a few options: for one, you could have a boolean flag that you set when you discover that the number isn't prime, and then check that and print your results after the inner for loop:

case 2:
    for(int j=0;j<10;j++){
        boolean isPrime = true; // assume it's prime
        for(i=2;i<array[j];i++){
            if(array[j]%i==0)
                isPrime = false;
                break; // get out of the inner for loop early
        }
        if(isPrime)
            System.out.println(array[j]+" is prime");
        else
            System.out.println(array[j]+" isn't prime");
    }
    break;

For a programming exercise, the answers given will do just fine. If this were a real application, using very large numbers, the algorithm that checks every possible divisor (or even the slight improvements on this) would be very slow.

Although it's possible to test for primality with certainty much more efficiently than this, in practice it's very, very efficient to check that a (very) large number is almost certainly prime. This is what gets used in cryptographic applications.

For further details, you could look up Miller-Rabin .

If you want an implementation you can use off-the-shelf, then convert your number to a BigInteger and then use BigInteger.isProbablePrime(int certainty) to determine whether it's probably prime. You can make the "probably" very close to certainty and it'll still be extremely efficient.

This is a function to check if a number is prime or not:

public static boolean isPrimeNumber(int number) {
    if (number == 2 || number == 3) {
        return true;
    }
    if (number % 2 == 0) {
        return false;
    }
    int sqrt = (int) Math.sqrt(number) + 1;
    for (int i = 3; i < sqrt; i += 2) {
        if (number % i == 0) {
            return false;
        }
    }
    return true;
}

You can call this function for every number you want to check.

Your case2 would be like:

 case 2:
    for(int j=0;j<10;j++){    
            if(!isPrimeNumber(array[j]))
                System.out.println(array[j]+" isn't prime");
            else
                System.out.println(array[j]+" is prime");
    }
    break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM