Sunteți pe pagina 1din 6

Q1. Write java program to find the factorial of a given number.

Define appropriate class and


methods in your program.

Answer:

import java.util.Scanner;
class FactorialDemo{
public static void main(String args[]){
//Scanner object for capturing the user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
//Stored the entered value in variable
int num = scanner.nextInt();
//Called the user defined function fact
int factorial = fact(num);
System.out.println("Factorial of entered number is: "+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}
OUTPUT:

• Method Summary

All MethodsStatic MethodsConcrete Methods


Modifier and Type Method and Description

(package private) fact(int n)


static int

static void main(java.lang.String[] args)

• Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll,


toString, wait, wait, wait

• Constructor Detail

• FactorialDemo[Show source in BlueJ]

FactorialDemo()

• Method Detail

• fact[Show source in BlueJ]

static int fact(int n)


• main

public static void main(java.lang.String[] args)


Q3. Create an applet which take a number as input. If the number is between 11-90 and is an even
number then display its table otherwise ask for other number as input.

Ans:- //Java program to Create an applet which take a number as input

import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Table extends Applet

{
private JLabel msg;
JTextField number;
public void init()
{
setLayout(new FlowLayout());
JLabel heading = new JLabel("Multiplication Table");
number = new JTextField(10);
JButton button = new JButton(" Press ");

msg = new JLabel("");


add(heading);
add(number);
add(button);
add(msg);
button.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{

String str=" ";int n = Integer.parseInt(number.getText());


if(n%2==0 && n>=11 && n <=90)
{
for(int i=1;i<=10;i++){str = str+ n*i+" ";
}
}
else
str = "Try Again!! Number must be Even and between 11-90";

msg.setText(str);
}
}
}
OUTPUT:
Q2. Write a program in java to read the content from a text file and count the number of
words in the file.

Ans:- //
OUTPUT:

S-ar putea să vă placă și