Lab Programs 12,13,14,15,16
Lab Programs 12,13,14,15,16
Create a folder inside Desktop folder with the name Pack1.compile and check.
package Pack1;
public class Example1{
public void packMethod()
{
System.out.println("packMethod() in Example1 class");
}
}
Save this outside the Pack1 folder and compile only in C://Desktop path
import Pack1.*;
public class B{
public static void main(String[] args)
{
Example1 e = new Example1();
e.packMethod();
}
}
15. Java program to find the factorial of a list of numbers reading input as command line argument.
public class Fact{
static long factorial(int n)
{
long fact=1;
for(int i=1;i<=n;i++){
fact*=i;
}
return fact;
}
public static void main(String[] args)
{
if(args.length==0){
System.out.println("Enter the numbers in command-line");
return;
}
System.out.println("Factorial of numbers:Below ");
for(String arg : args){
int num=Integer.parseInt(arg);
System.out.println("Factorial of "+num+" is "+factorial(num));
}
}
}
16. Java program to display all prime numbers between two limits.
import java.util.Scanner;
public class Prime{
static boolean isPrime(int num) {
if (num < 2)
return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0)
return false;
}
return true;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter lower limit: ");
int lower = s.nextInt();
System.out.print("Enter upper limit: ");
int upper = s.nextInt();
System.out.println("Prime numbers between " + lower + " and " + upper + ":");
for (int i = lower; i <= upper; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
s.close();
}
}