Java Program to display Prime Numbers using Exception Handling
Write a Java Program to display Prime Numbers using Exception Handling….
In this program , we input from the user to enter the last limit upto which he/she wants to display prime no.s.
We used function to check for the prime number and exception Handling for removing bugs or Errors from the Code….
Here below is the source code of the program to find prime numbers using functions….
SOURCE CODE ::
import java.util.Scanner; public class Prime_numbers { public static void main(String[] args) { int n,i=2,j=2; Scanner sc = new Scanner(System.in); System.out.println("ENter upto which no. u want :"); try{ n=sc.nextInt(); if(n>0) { System.out.println("Prime Numbers are : "); prime(n); System.out.println(""); } else { System.out.println("Please enter only positive integer "); } } catch(Exception e) { System.out.println(e); System.out.println("Please enter only integer "); } } //Function to print prime numbers......... static void prime(int a) { int i=2,j=2; while(a>i) { //Checking wheather number is prime no. or not....... while(true) { if(i%2==0) { break; } if(i%j==0) { break; } else { j++; } } if(j==i) { System.out.print(" "+ i); j=2; } i++; } } }
OUTPUT ::
ENter upto which no. u want : 100 Prime Numbers are : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 95 97