Java-Lab 4
Java-Lab 4
String res;
String mob;
Scanner sc=new Scanner(System.in);
res=sc.next();
mob=sc.next();
try{
if(res.length()!=9 || mob.length()!=10){
throw new IllegalArgumentException();
}
for(char c: mob.toCharArray()){
if(!Character.isDigit(c)){
throw new NumberFormatException();
}
}
}
}
System.out.println("Valid");
}
catch(Exception e){
System.out.println("Invalid "+e);
}
}
Output:
2. Write a program to demonstrate the knowledge of students in
working with user-defined packages and sub-packages. Eg.,
Within the package named ‘primespackage’, define a class
Primes which includes a method checkForPrime() for checking
if the given number is prime or not. Define another class named
TwinPrimes outside of this package which will display all the
pairs of prime numbers whose difference is 2. (Eg, within the
range 1 to 10, all possible twin prime numbers are (3,5), (5,7)).
The TwinPrimes class should make use of the checkForPrime()
method in the Primes class.Write a program that count how
many prime numbers between minimum and maximum values
provided by user. If minimum value is greater than or equal to
maximum value, the program should throw a InvalidRange
exception and handle it to display a message to the user on the
following format:Invalid range: minimum is greater than or
equal to maximum. For example, if the user provided 10 as
maximum and 20 as minimum, the message should be: Invalid
range: 20 is greater than or equal to 10.
package Primes
public class Primes1
{
public bool isprime(int n){
int c=0;
for(int i=2;i<=Math.sqrt(n);i++){
if(n%i==0){
c++;
break;
}
}
if(c>0){
return false;
}else{
return true;
}
}
import Primes.Primes1;
import java.util.Scanner;
package Main;
public class Main
{//twin prime class
public static void main(String[] args) {
try{
if(start>=end){
throw new Exception("Invalid range: minimum is
greater than or equal to maximum");
}
}catch(Exception e){
System.out.println(e);
if(p.isprime(i)&& p.isprime(i-2)){
System.out.println(""+(i-2)+" "+i+"are twin primes");
}
}
}
}