Release of exceptions as a function of prime number

Asked

Viewed 126 times

1

Write a function that receives a number, throw an exception if the number is not positive and return 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)

  • 1

    Normally I would use IllegalArgumentException. Use only Exception is generally a bad programming practice.

  • Did any of the answers solve your problem? Do you think you can accept one of them? If you haven’t already, see [tour] how to do this. You would help the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site.

2 answers

4

Normally I would not use exception for this, I think an abuse, it is good to make the function not print anything and return the result to print off it, so separates the responsibilities. I do not find suitable exception in many situations, launch Exception even though it’s too generic. But if you want to do it, this would be it:

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;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Read this: Why should we avoid returning error codes?. Look for more about the subject on the website.

3

It can even 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 working

  • From what I understand it seems he’s worried about the exception.

  • @bigown because I didn’t notice it like that. Let’s see what he says ;)

  • This question is from a list of college exercises. From what I understand, the teacher wants to write a single function that plays an exception if the number is negative (Illegalargumentexception) and returns true if the number is prime. But I realized that it is also necessary to check if the number received is zero.

  • @Caio_ignatz then the reply from the bigown answers your question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.