Craker Box
Craker Box

Reputation: 17

Prime Number checker shows no errors but spits out an error when is executed.. how to fix this?

This block of code shows no errors in eclispe yet when executed it shows this:

Exception in thread "main" java.lang.ArithmeticException: / by zero at prime_number.main(prime_number.java:15)

Code below:

import java.util.Scanner;
public class prime_number {

    public static void main(String[] args) {
        
        int temp;
        boolean isPrime=true;
        
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter any number: ");
        int num = scan.nextInt();
        scan.close();
        
        for(int i = 0; i<num;i++) {
            temp=num%i;
            if(temp==0) {
                isPrime=false;
                break;
            }
        }
        if(isPrime==true) {
            System.out.println(num+" is a Prime number!");
        
        }
        else {
            System.out.println(num+" is not a Prime Number!");
        }
    }
}

Upvotes: 0

Views: 37

Answers (2)

Aniketh Malyala
Aniketh Malyala

Reputation: 2660

Start your for loop from i=1, because when you do:

temp = num % i;

you are actually doing division by 0.

If you really want, you can start your for loop from i = 2, because i = 1 will always be factor of your number, given it is a whole number.

Upvotes: 1

enzo
enzo

Reputation: 11496

In the first iteration of your for-loop, i == 0.

When it reaches the line

temp = num % i;

the program tries to divide num by i and evaluate the division remainder. Since you can't divide by zero, the program throws the error.

Upvotes: 1

Related Questions