Quest 1 define a class batsman with the following specifications
1. Quest 1 Define a class batsman with the following specifications:
Private members:
bcode 4 digits code number
bname 20 characters
innings, notout, runs integer type
batavg it is calculated according to the formula –
batavg =runs/(innings-notout)
calcavg() Function to compute batavg
Public members:
readdata() Function to accept value from bcode, name, innings, &
notout and invoke the function calcavg()
displaydata() Function to display the data members on the screen.
importjava.util.Scanner;
classbatsman
{
private intbcode;
private Stringbname;
private intinnings,notout,runs;
double batavg;
private voidbatavg()
{
}
private voidcalcavg()
{
batavg =runs/(innings-notout);
4. A member function CALCNTR() to calculate and return the number of centers as
(NoCandidates/100+1)
Public Members
- A function SCHEDULE() to allow user to enter values for TestCode, Description,
NoCandidate & call function CALCNTR() to calculate the number of Centres
- A function DISPTEST() to allow user to view the content of all the data members
importjava.util.Scanner;
classTest {
private inttestcode;
private StringDes;
private intnocandi;
private intcalcntr()
{
return(nocandi/100+1);
}
publicvoidschedule()
{
Scanners = newScanner(System.in);
System.out.print("Enterthe testcode values:");
testcode = s.nextInt();
System.out.print("Enterthe description:");
Des= s.next();
System.out.print("No.of candidate:");
nocandi = s.nextInt();
calcntr();
}
publicvoiddisptest()
{
6. A data member Destinationof type string
A data member Distance of type float
A data member Fuel of type float
A member function CALFUEL() to calculate the value of Fuel as per the
following criteria
Distance Fuel
<=1000 500
more than 1000 and <=2000 1100
more than 2000 2200
Public Members
A function FEEDINFO()to allow user to enter values for Flight Number,
Destination, Distance & call function CALFUEL() to calculate the quantity of
Fuel
A function SHOWINFO()to allow userto view the content of all the data
members
importjava.util.Scanner;
classflight
{
private intflight_no;
private Stringdestination;
private floatdistance;
private floatfuel;
private voidcalfuel()
{
if (distance<=1000)
fuel=500;
else if(distance>=2000)
fuel=1000;
else fuel=2200;
8. ft.FEEDINFO();
ft.SHOWINFO();
}
}
Quest4. Define a class BOOKwith the following specifications :
Private members of the class BOOKare
BOOK NO integer type
BOOKTITLE 20 characters
PRICE float (price per copy)
TOTAL_COST() A function to calculate the total costfor N number of
copies
where N is passedto the function as argument.
Public members of the class BOOKare
INPUT() function to read BOOK_NO. BOOKTITLE, PRICE
PURCHASE() function to ask the user to input the number of copies to
be
purchased. It invokes TOTAL_COST()and prints the
total
11. }
}
Quest5. Define a class REPORTwith the following specification:
Private members :
adno 4 digit admissionnumber
name 20 characters
marks an array of 5 floating point values
average average marks obtained
GETAVG() a function to compute the average obtainedin five
subject
Public members:
READINFO() function to acceptvalues for adno, name, marks. Invoke
the function GETAVG()
DISPLAYINFO() function to display all data members of report on the
screen.
importjava.util.*;
classReport
{
13. publicstaticvoidmain(String[] args)
{
Reportobj=newReport();
obj.readinfo();
obj.displayinfo();
}
}
Q6. Define a class student with the following specification
Private members of class student
admno integer
sname 20 character
eng. math, science float
total float
ctotal() a function to calculate eng + math + science with float return type.
Public member function of class student
Takedata() Function to accept values for admno, sname, eng, science
and invoke ctotal() to calculate total.
Showdata() Function to display all the data members on the screen
importjava.util.Scanner;
16. Q7. Define a class Telephone
Data Members :
intprv,pre - to store the previous and present meter reading
int call - to store call made (pre-prv)
String name - to store name of the customer
doubleamt - to store amount
double total - to store total amount
member Methods
void input() -to get the value for previous, present reading and the
name of the customer
voidcal() - to calculate amount and total amount
void display() -to display the name , calls made, amount and total
amount to be paid in the following format.
Name Calls Made Amount Total Amount
-------- ------------ ----------- ------------------
Calls made Rate
Upto 100 calls No charge
For the next 100 calls 90 paisa per call
17. For the next 200 calls 80 paisa per call
More than 400 calls 70 paisa per call
Every customer has to pay Rs. 180 per month as monthly rent for the services.
importjava.util.Scanner;
classTelephone
{
intprv,pre;
intcall;
Stringname;
double amt;
double total;
voidinput()
{
Scanners = newScanner(System.in);
System.out.println("Enterthe Customername :");
name = s.next();
System.out.println("Enterthe presentmeterreading");
pre = s.nextInt();
System.out.println("Enterthe previousmeterreading");
prv = s.nextInt();
System.out.println("totalcallsis:");
call = (pre-prv);
}
18. voidcal()
{
if(call<100)
{
System.out.println("charge rupee 180/- for montlyservices:");
System.out.println("noothercharge ** Enjoy**");
amt = 0.0;
total = 180.0;
}
else if(call<=200)
{
System.out.println("charge rupee 180/- for montlyservices:");
System.out.println("chargesis:");
amt = 100*0.90;
total = 180+amt;
}
else if(call<=400)
{
amt = (100*0.90)+(200*0.80);
total = 180+amt;
}
else
{
amt = 0.40*call;
20. Q8. (The Triangle class) Designa class named Triangle that extends
GeometricObject. The class contains:
■ Three double data fields named side1, side2, and side3 with default values 1.0 to denote
three sides of the triangle.
■ A no-arg constructor that creates a default triangle.
■ A constructor that creates a triangle with the specified side1, side2, and side3.
■ The accessormethods for all three data fields.
■ A method named getArea() that returns the area of this triangle.
■ A method named getPerimeter() that returns the perimeter of this triangle.
■ A method named toString() that returns a string description for the triangle.
The toString() method is implemented as follows:
return "Triangle: side1 = " + side1 + " side2 = " + side2 +
" side3 = " + side3;
For the formula to compute the area of a triangle. Implement the class. Write a test
program that creates a Triangle object with sides 1, 1.5, 1, color yellow and filled true, and
displays the area, perimeter, color, and whether filled or not.
classGeometricObject
{
private Stringcolor= "Yellow";
private Booleanfilled=true;
25. Q9. (The Person, Student, Employee, Faculty, and Staff classes) Designa class named
Person and its two subclasses named Student and Employee. Make Faculty and Staff
subclasses of Employee. A person has a name, address, phone number, and email address.
A student has a class status (freshman, sophomore, junior, or senior). Define the status as a
constant. An employee has an office, salary, and date hired. Define a class named MyDate
that contains the fields year, month, and day. A faculty member has office hours and a
rank. A staff member has a title. Override the toString method in each class to display the
class name and the person’s name. Implement the classes. Write a test program that
creates a Person, Student, Employee, Faculty, and Staff, and invokes their toString()
methods.
importjava.util.Scanner;
classmydate
{
intd,m,y;
publicvoidgetdate()
{
Scannerin=newScanner(System.in);
System.out.print("Enterday:");
d=in.nextInt();
32. }
}
Q.19. Write a program using AWT/swings or create a GUI in application for a simple
calculator. (use proper layout).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class calculator extends JApplet
{
public static void main(String[] args)
{
JFrame window = new JFrame("Simple Calculator");
CalcPanel content = new CalcPanel();
window.setContentPane(content);
window.pack();
window.setLocation(100,100);
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
}
public void init() {
setContentPane( new CalcPanel() );
}
public static class CalcPanel extends JPanel implements ActionListener
{
private JTextField xInput, yInput;
33. private JLabel answer;
public CalcPanel() {
setBackground(Color.GRAY);
setBorder( BorderFactory.createEmptyBorder(5,5,5,5) );
xInput = new JTextField("0", 10);
xInput.setBackground(Color.WHITE);
yInput = new JTextField("0", 10);
yInput.setBackground(Color.WHITE);
JPanel xPanel = new JPanel();
xPanel.add( new JLabel(" x = "));
xPanel.add(xInput);
JPanel yPanel = new JPanel();
yPanel.add( new JLabel(" y = "));
yPanel.add(yInput);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,4));
JButton plus = new JButton("+");
plus.addActionListener(this);
buttonPanel.add(plus);
JButton minus = new JButton("-");
minus.addActionListener(this);
buttonPanel.add(minus);
JButton times = new JButton("*");
times.addActionListener(this);
buttonPanel.add(times);
JButton divide = new JButton("/");
divide.addActionListener(this);
buttonPanel.add(divide);
answer = new JLabel("x + y = 0", JLabel.CENTER);
answer.setForeground(Color.red);
answer.setBackground(Color.white);
answer.setOpaque(true);
setLayout(new GridLayout(4,1,3,3));
add(xPanel);
add(yPanel);
add(buttonPanel);
add(answer);
xInput.requestFocus();
}
public void actionPerformed(ActionEvent evt) {
double x, y;
try
{
String xStr = xInput.getText();
x = Double.parseDouble(xStr);
}
34. catch (NumberFormatException e) {
answer.setText("Illegal data for x.");
xInput.requestFocus();
return;
}
try {
String yStr = yInput.getText();
y = Double.parseDouble(yStr);
}
catch (NumberFormatException e) {
answer.setText("Illegal data for y.");
yInput.requestFocus();
return;
}
String op = evt.getActionCommand();
if (op.equals("+"))
answer.setText( "x + y = " + (x+y) );
else if (op.equals("-"))
answer.setText( "x - y = " + (x-y) );
else if (op.equals("*"))
answer.setText( "x * y = " + (x*y) );
else if (op.equals("/")) {
if (y == 0)
answer.setText("Can't divide by zero!");
else
answer.setText( "x / y = " + (x/y) );
}
}
}
}
35. Q.20. Write a program to generate a sequence of Fibonacci Strings as follows:
S0 = “a”, S1 = “b”, Sn = S(n-1) + S(n-2) where ‘+’ denotes concatenation. Thus the
sequence is:
a, b, ba, bab, babba, babbabab, ………. n terms and add this generated series to a file
named as fibo.txt.
import java.io.*;
36. import java.lang.*;
import java.util.*;
class fibo
{
public static void main(String[] args)
{
FileOutputStream fout=null;
try{
fout = new FileOutputStream("fibo.txt");
char ch='y',t,ar[];
String s1="a",s2="b",s3=null;
t= s1.charAt(0);
fout.write(t); fout.write(' ');
t= s2.charAt(0);
fout.write(t);fout.write(' ');
Scanner reader = new Scanner(System.in);
do
{
s3=s1+s2; s1=s2; s2=s3;
ar=s3.toCharArray();
for(int i=0;i<s3.length();i++)
fout.write(ar[i]);
fout.write(' ');
System.out.println(" do you want to continue?(y/n)");
ch = reader.next().charAt(0);
}
while(ch!='n');
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally{
try{
fout.close();
}
catch(IOException e){}
}
37. }
}
Q21. Write a temperature conversion program using GUI either application or applet that
converts from Fahrenheit to Celsius. The Fahrenheit temperature should be entered from
keyboard(via textfield) and another textfield should be used to display the converted
temperature. (use a proper layout for the screen)
Use the following formula for the conversion.
Celsius=5/9 * (Fahrenheit -32)
import javax.swing.*;
import java.awt.event.*;
38. class Converter extends JFrame
{
Converter()
{
super("Converter");
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
JLabel l1=new JLabel("Enter in Fehrenheit");
final JTextField t1=new JTextField(25);
JButton b=new JButton("Convert To celsius");
JLabel l2=new JLabel("Value in Celsius");
final JTextField t2=new JTextField(25);
t2.setEditable(false);
l1.setBounds(20,50,200,25);
t1.setBounds(200,50,200,25);
b.setBounds(100,100,150,25);
l2.setBounds(20,150,200,25);
t2.setBounds(200,150,200,25);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
try {
double
fahrenheit=Double.parseDouble(t1.getText());
System.out.println(fahrenheit);
t2.setText(""+0.5555*(fahrenheit-32));
}
catch(NumberFormatException nfe){
nfe.printStackTrace();}
}});
add(l1);
add(t1);
add(l2);
add(t2);
add(b);
}
public static void main(String a[])
{
new Converter();
}
}
39. Q.22. Create an applet which will have three radio buttons for color RED, GREEN, BLUE
on selection of a radio button the background color should be change accordingly.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<APPLET CODE="choice" WIDTH=400 HEIGHT=400>
</APPLET>*/
public class choice extends Applet implements ItemListener
{
Checkbox cb1,cb2,cb3;
CheckboxGroup cbg=null;
public void init()
{
cbg=new CheckboxGroup();
41. Output:
Q.23. Write a program to create two threads, one thread will print odd numbers and
second thread will print evennumbers between 1 to 10.
import java.lang.*;
import java.util.*;
class even extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
if((i%2)==0)
System.out.println("Even no. "+i);
}
}
}
class odd extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
if((i%2)!=0)
System.out.println("Odd no. "+i);
}
}
}
class Evenodd
{
public static void main(String[] args)
{
odd od=new odd();
even evn=new even();
od.start();
42. evn.start();
}
}
Q24. (Loan calculator):Write an applet for calculating loan payment, as shown in below
Figure. The user can enter the interest rate, the number of years, and the loan amount and
click the Compute Payment button to display the monthly payment and total payment.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.lang.Math;
/*<applet code="loan" width=300 height=400>
45. Q25. An electronic shop has announced the following seasonal discounts on the purchase of
certain items
Purchase amount Discount on Laptop Discount of Desktop PC
0-25000 0.0% 5.0%
25001-57000 5.0% 7.5%
57001-100000 7.5% 10.0%
More than 100000 10.0% 15.0%
Designa class electronic having data members as name, address, amount of purchase and
the type of purchase(desktop or laptop) . Computer and print the net amount
import java.lang.*;
import java.util.*;
class electronics
47. case 1: e.type="Laptop"; break;
case 2: e.type="DesktopPC"; break;
default: System.out.println("entered wrong choice"); break;
}System.out.println("enter amount");
e.amount=reader.nextDouble();
e.compute(e.type,e.amount);
}
}
Q26. Write a java program to calculate area of different shape (minimum 5 for eq. –
square, rectangle….) by using method overriding concept.
import java.lang.*;
import java.util.*;
class square
{
double s1;
square(double a)
{
s1=a;
}
double area()
{
return s1*s1;
}
}
48. class rectangle extends square
{
double s2;
rectangle(double a,double b)
{
super(a); s2=b;
}
double area()
{
return s1*s2;
}
}
class triangle extends square
{
double s2;
triangle(double a,double b)
{
super(a); s2=b;
}
double area()
{
return s1*s2/2;
}
}
class circle extends square
{
circle(double a)
{
super(a);
}
double area()
{
return 3.14*s1*s1;
}
}
class rhombus extends square
{
double s2;
rhombus(double a,double b)
{
super(a); s2=b;
}
double area()
{
49. return s1*s2/2;
}
}
class area
{
public static void main(String[] args)
{
square s1= new square(15.0);
rectangle r1= new rectangle(12.0,13.0);
triangle t1= new triangle(8.0,5.0);
circle c1= new circle(6.0);
rhombus rm1= new rhombus(11.0,9.0);
square s2;
s2=s1; System.out.println("Area of Square :" +s2.area());
s2=r1; System.out.println("Area of rectangle :" +s2.area());
s2=t1; System.out.println("Area of triangle :" +s2.area());
s2=c1; System.out.println("Area of circle :" +s2.area());
s2=rm1; System.out.println("Area of rhombus :" +s2.area());
}
}
50. Q27. Write a program that prompts the user to enter the name of an ASCII text file and
display the frequency of the characters in the file.
import java.io.*;
class q27
{
static int temp[]=new int[255];
public static void main(String[] args)
{
FileInputStream fin=null;
char c;
try{
fin=new FileInputStream (args[0]);
do
{
c=(char)fin.read();
if(c!='q')
temp[c]++;
else break;
} while(c!=-1);
for(int i=0;i<255;i++)
{
if(temp[i]>0)
System.out.println("char :"+(char)i+" frequency :"+temp[i]);
}
}catch (IOException e) {
e.printStackTrace();
}
finally{
try{fin.close();
}
catch(IOException e) {}}
}
}
51. Q28. (Creating an investment-value calculator) Write a program that calculates the future
value of an investment at a given interest rate for a specified number of years. The formula
for the calculation is as follows:
futureValue = investmentAmount * (1 + monthlyInterestRate)years*12
Use text fields for interest rate, investment amount, and years. Display the future amount
in a text field when the user clicks the Calculate button, as shown in Figure.