In: Computer Science
JAVA PROGRAM
1. Write a program to find the factorial value of any non-negative number entered through the keyboard.(method) (Factorial of n: n! = 1*2*3*…*n, 0! = 1.)
2. Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. (method)
Please post a screenshot of the codes. Thanks!
(1)
import java.util.Scanner;
//creating class factorial
public class Factorial {
//Declare method for calculating factorial
public int fact(int fact)
{
int f=1;
for(int i=fact;i>0;i--)
{
f=f*i;
}
return f;
}
//main method
public static void main(String[] args) {
//creating data variable
int num;
int fact = 1;
//creating object of scanner class for taking input
from user
Scanner input=new Scanner(System.in);
//creating object of our class
Factorial fc=new Factorial();
System.out.print("Enter a number: ");
//taking input from user
num=input.nextInt();
//check number is greater then 0 or not
if(num>=0)
{
fact=fc.fact(num);
System.out.println("Factorial of "+num +" is
:"+fact);
}
else {
System.out.println("plz entered
value greater then 0");
}
input.close();
}
}
screenshot -
Output-
(2)
import java.util.Scanner;
//creating class prime
public class Prime {
//Declare method prime for check number is prime or
not
public void isPrime(int num)
{
int i,m=0,flag=0;
m=num/2;
if(num==0||num==1){
System.out.println(num+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(num%i==0){
System.out.println(num+" is not prime number");
flag=1;
break;
}
}
if(flag==0) { System.out.println(num+" is prime
number"); }
}
}
public static void main(String[] args) {
//creating object of scanner class for taking input
from user
Scanner input=new
Scanner(System.in);
//creating object of our
class
Prime prime=new Prime();
System.out.print("enter positive
Integer: ");
//taking input from user
int num=input.nextInt();
if(num>=0)
{
//calling method
isPrime
prime.isPrime(num);
}
else {
System.out.println("Please enter a positive number");
}
input.close();
}
}
screenshot-
Output-