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)
Normally I would use
IllegalArgumentException
. Use onlyException
is generally a bad programming practice.– Victor Stafusa
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.
– Maniero