Launching exceptions based on prime number

1
  

Write a function that receives a number, throws an exception if the number is not positive and returns true if it is prime, or false, otherwise.

My answer:

public static void main(String []args) throws Exception{
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    if(n <= 0){
        throw new Exception("Número não pode ser menor ou igual à zero!");
    }
    else{
        primo(n);
    }
}
public static void primo(int n){
    int contador = 0;

    for(int j = 1; j <= Math.sqrt(n); j++){
        if(n % j == 0){
            contador++;
            if(contador == 2){
                break;
            }
        }
    }
    if(contador == 1){
        System.out.println("Verdadeiro");
    }
    else{
        System.out.println("Falso");
    }
}

How can I rewrite my answer in the form of a single Boolean function?

Ex: public static boolean f(int n)

    
asked by anonymous 19.08.2016 / 18:46

2 answers

4

Normally I would not use exception for this, I find an abuse, it is good to make the function not print anything and return the result to print out of it, so separates the responsibilities. I do not find an exception to be appropriate in many situations, casting Exception less even though it is too generic. But if you want to do it, it would be this:

import java.util.*;

class Ideone {
    public static void main(String []args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        try {
            System.out.println(primo(n) ? "Verdadeiro" : "Falso");
        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        }
    }
    public static boolean primo(int n) throws IllegalArgumentException {
        if (n <= 0) {
            throw new IllegalArgumentException("Número não pode ser menor ou igual à zero!");
        }
        int contador = 0;
        for (int j = 1; j <= Math.sqrt(n); j++){
            if (n % j == 0) {
                contador++;
                if (contador == 2) {
                    return false;
                }
            }
        }
        return true;
    }
}

See running on ideone .

Read this: Why should we avoid returning error codes? . You can find more about the subject on the site .

    
19.08.2016 / 19:09
3

It can simplify a lot:

public static boolean primo( int n )
{
    int contador = 0;

    for( int j = 1; j <= Math.sqrt( n ); j++ )
        if( n % j == 0 )
            if( ++contador == 2 )
                return false;

    return true;
}

See it working

    
19.08.2016 / 19:05