Professional Documents
Culture Documents
Lab Week 1-12
Lab Week 1-12
DEPARTMENT OF COMPUTER
SCIENCE
WEEK NO.
PAGE NO.
SIGNATURE
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE
i) Finds the round value of 'num' and stores the result in a variable
numRound of type double.
ii) Finds the ceil value of 'num' and stores the result in a variable
numCeil of type double.
6# iii) Finds the floor value of 'num' and stores the result in a variable
numFloor of type double.
Cast 'num' to type int and store the result in a variable numInteger
of type int.Display output of numRound, numCeil, numFloor, and
numInteger on screen.
Note: Test your program with the following value of num
num=56.764num=36.432
Write a java program to calculate simple interest and compound
7# interest on a certain sum for a certain time at a certain rate of
interest.
PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE
Write a java program to print the squares and cubes for the
2#
numbers 1 to 5.
1
23
456
7 8 9 10
11 12 13 14
15 16 17 18 19
WEEK 2
1
01
101
0101
10101
010101
Write a program in the sequence 0, 1, 1, 2, 3, 5, 8, 13, 21…..is
6# called Fibonacci numbers. Write a program using a do while
loop to calculate and print the first m Fibonacci numbers.
WEEK NO.
SIGNATURE
PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE
WEEK NO.
SIGNATURE
PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE
Write a Java class Clock for dealing with the day time
represented by hours, minutes, and seconds. Your class must
7# have the following features:
Three instance variables for the hours (range 0 - 23), minutes
(range 0 - 59), and seconds (range 0 - 59).
Three constructors:
• default (with no parameters passed; is should initialize the
represented time to 12:0:0)
• a constructor with three parameters: hours, minutes, and
seconds.
• a constructor with one parameter: the value of time in seconds
since midnight (it should be converted into the time value in
hours, minutes, and seconds)
Instance methods:
• a set-method method setClock() with one parameter seconds
since midnight (to be converted into the time value in hours,
minutes, and seconds as above).
• get-methods getHours(), getMinutes(), getSeconds() with no
parameters that return the corresponding values.
• set-methods setHours(), setMinutes(), setSeconds() with one
parameter each that set up the corresponding instance
variables.
• method tick() with no parameters that increments the time
stored in a Clock object by one second.
WEEK 4
SIGNATURE
PAGE NO.
WEEK NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
Methods:
SIGNATURE
WEEK NO.
PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
• Instance variables :
o realPart for the real part of type double
o imaginaryPart for imaginary part of type double.
6# • Constructor:
o public Complex (): A default constructor, it should
initialize the number to 0, 0)
o public Complex (double realPart, double
imaginaryPart): A constructor with parameters, it
creates the complex object by setting the two fields to
the passed values.
• Instance methods:
o public Complex add (Complex otherNumber):
SIGNATURE
WEEK NO.
PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE
WEEK NO.
PAGE NO.
SIGNATURE
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
• Instance variables :
o firstName for the author’s first name of type String.
o lastName for the author’s last name of type String.
• Constructor:
o public Author (String firstName, String lastName): A
6# constructor with parameters, it creates the Author
object by setting the two fields to the passed values.
• Instance methods:
o public void setFirstName (String firstName): Used to
set the first name of author.
o public void setLastName (String lastName): Used to
set the last name of author.
• Instance variables :
o title for the title of book of type String.
o author for the author’s name of type String.
o price for the book price of type double.
• Constructor:
o public Book (String title, Author name, double price):
WEEK 8
SIGNATURE
PAGE NO.
WEEK NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
Write a Java program which reads student grades from a
text file called grades.txt and prints only the
corresponding letter grades into a file called letter.txt.
The letter grades are assigned according to the following
table. Assume that the grades.txt file can have any
number of students’ grades. Hint:The last number in the
grades.txt file is -1
1#
WEEK 9
SIGNATURE
PAGE NO.
WEEK NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
Write applets to draw the following shapes:
1#
a)Cone b)Cylinder c)Square inside a circle
3#
PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
Write a graphics program that draws a clock face with a
time that the user enters in a text field. (The user must
enter the time in the format hh:mm, for example09:45).
Hint: You need to find out the angles of the hour hand and
the minute hand. The angle of the hour hand is harder; it
travels 360 degrees in 12 x 60 minutes. Your output must
1# be in the following format:
Sample Output:
2#
4#
PAGE NO.
SIGNATURE
WEEK NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
SIGNATURE
WEEK NO.
PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
Write a java program to perform calculations like addition,
subtraction, multiplication, and division using AWT and
applets. Create three Text Fields for entering a first
number, the second number, and displaying the result.
Add four buttons for performing addition, subtraction,
multiplication, and division.
1#
WEEK 13
WEEK NO.
SIGNATURE
PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
WEEK 14
WEEK 1
#1 Write a java program to print ‘Hello World ’.
This is the required code:
package javaapplication1;
public class JavaApplication1 {
public static void main(String[] args){
System.out.println("hello");
}
}
And this is its output:
package javaapplication1;
public class JavaApplication1 {
public static void main(String[] args){
System. out.println(“College View Apartment, Dhorra Mafi, Aligarh");
}
}
OUTPUT:
package javaapplication1;
import java.util.Scanner;
public class week1Q3 {
public static void main(String[] args)
{ Scanner a=new Scanner(System.in);
System.out.println("Enter first number: ");
int x=a.nextInt();
System.out.println("Enter second number: ");
int y=a.nextInt();
int sum;
sum=x+y;
System.out.println("Sum of the two numbers is: "+sum);
}
}
And this is its output:
package javaapplication1;
import java.util.Scanner;
public class week1Q4 {
public static void main(String[] args) {
#5 Write a java program for finding the sum, difference, product, quotient,
minimum and maximum of any two integers.
This is the required code:
package javaapplication1;
import java.util.Scanner;
import java.lang.Math;
public class Week1Q5 {
package javaapplication1;
import java.util.Scanner;
import java.lang.Math;
public class Week1Q6 {
public static void main(String[] args){
double num;
Scanner s=new Scanner(System.in);
System.out.println("Enter the value: ");
num=s.nextDouble();
double numRound=Math.round(num);
System.out.println("The round value of entered number is: "+numRound);
double numCeil=Math.ceil(num);
System.out.println("The ceil value of entered number is: "+numCeil);
double numFloor=Math.floor(num);
package javaapplication1;
import java.util.Scanner;
import java.lang.Math;
public class Week1Q7 {
public static void main(String[] args){
double P,R,T,SI,CI;
Scanner s=new Scanner(System.in);
System.out.println("Enter the principal amount: ");
P=s.nextDouble();
System.out.println("Enter the rate of interest: ");
R=s.nextDouble();
System.out.println("Enter the time duration: ");
T=s.nextDouble();
BILAL AHMAD 21CAMSA 111 30
LAB COURSE-II | CAMS-20P1
SI=(P*R*T)/100;
System.out.println("The value of simple interest is: "+SI);
CI=P*Math.pow(1+(R/100),T)-P;
System.out.println("The value of compound interest is: "+CI);
}
}
#10 Write a java program to interchange the value of two variables. (Note:
both ways using temporary variable and not using any other value).
package javaapplication1;
import java.util.Scanner;
public class week1q10 {
public static void main(String[] args){
int x,y,z;
Scanner s=new Scanner(System.in);
System.out.println("Enter value of first variable x: ");
x=s.nextInt();
System.out.println("Enter value of second variable y: ");
y=s.nextInt();
z=x;
x=y;
y=z;
System.out.println("Value after swapping becomes: ");
System.out.println("x= "+x+" y= "+y);
}
}
And this is its output:
package javaapplication1;
import java.util.Scanner;
public class WEEK1Q10withoutthirdvariable {
public static void main(String[] args){
int x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter value of first variable x: ");
x=s.nextInt();
System.out.println("Enter value of second variable y: ");
y=s.nextInt();
x=x+y;
y=x-y;
x=x-y;
System.out.println("Value after swapping becomes: ");
System.out.println("x= "+x+" y= "+y);
}
}
And this is its output:
WEEK 2
WEEK 2
#1 Write a java program to prints the count of odd and even no’s entered.
package javaapplication1;
import java.util.Scanner;
public class week2Q1 {
public static void main(String[] args) {
int n,e=0,o=0;
Scanner a=new Scanner(System.in);
System.out.println("Enter the amount of numbers you wish to enter");
n=a.nextInt();
for(int i=0;i<=n;i++){
System.out.println("Enter the value of "+i+" number");
int b=a.nextInt();
if(b%2==0) {
e++; }
else {
o++; }
}
System.out.println("Number of even numbers entered is: "+e);
System.out.println("Number of odd numbers entered is: "+o);
}
}
#2 Write a java program to print the squares and cubes for the numbers 1 to
5.
This is the required code:
package javaapplication1;
import java.util.Scanner;
import java.lang.Math;
public class week2Q2 {
public static void main(String[] args) {
int sq,cube;
for(int i=0;i<=5;i++)
{ sq=(int) Math.pow(i, 2);
System.out.println("Square of number "+i+" is: "+sq);
cube= (int) Math.pow(i,3);
System.out.println("Cube of number "+i+" is: "+cube); }
}
}
package javaapplication1;
import java.util.Scanner;
public class Week2Q3 {
public static void main(String[] args){
double sum=0;
for(double i=1;i<=10;i++) {
sum=sum+1/i; }
System.out.println("Sum of the reciprocals 1/1+1/2+1/3+1/4+ --- --- --- --- --- --- ---+1/10 is: ");
System.out.println(sum);
} }
package javaapplication1;
import java.util.Scanner;
public class week2Q4 {
public static void main(String[] args){
Scanner a=new Scanner(System.in);
System.out.println("Enter the number of even numbers for which sum is to be computed: ");
int N=a.nextInt();
int sum=0;
int b=0;
for(int i=1;i<=N;i++){
b=b+2;
sum+=b;
}
System.out.println("Sum of "+N+" even integers is: "+sum);
}
}
1
23
456
7 8 9 10
11 12 13 14
15 16 17 18 19
i) Write a program to print the above triangle.
ii) Modify the program to produce the following form of Floyd’s triangle.
1
01
101
0101
10101
010101
package javaapplication1;
public class WeekQ5 {
public static void main(String[] args){
System.out.println("Floyd's triangle will be : ");
int k=1;
for(int j=1;j<=6;j++){
for(int i=1;i<=j;i++){
if(i==5) {
continue; }
System.out.print(k + " ");
k++; }
System.out.println(); }
} }
And this is its output:
(ii) Given below is the required code for the given triangle:
package javaapplication1;
public class Week2q5ii {
public static void main(String[] args) {
int p,q;
for(int i=1;i<=6;++i) {
if (i%2==0) {
p=1;
q=0; }
else{
p=0;
q=1; }
for(int j=1;j<=i;++j) {
if(j%2==0) {
System.out.print(p+""); }
else{
System.out.print(q+""); }
}
System.out.println();
} } }
And this is its output:
package javaapplication1;
import java.util.Scanner;
public class week2Q6 {
public static void main(String[] args){
Scanner a=new Scanner(System.in);
int m;
System.out.println(“Enter the number of terms of fibonacci sequence that u wish to compute: “);
m=a.nextInt();
int i=1;
int n1=0;
int n2=1;
int n3=0;
System.out.print(“fibonacci series till “+m+”terms is: “);
do{
System.out.println(n1+” ,”);
BILAL AHMAD 21CAMSA 111 43
LAB COURSE-II | CAMS-20P1
n3=n1+n2;
n1=n2;
n2=n3;
i++;
}
while(i<=m);
}
}
And this is its output:
package javaapplication1;
import java.util.Scanner;
public class week2q7 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter the number for which multiplication table must be printed: ");
int n;
n=s.nextInt();
int product = 0;
System.out.println("Table of"+n+"is: ");
BILAL AHMAD 21CAMSA 111 44
LAB COURSE-II | CAMS-20P1
for(int i=1;i<=10;i++){
product=n*i;
System.out.println(n+" * "+i+" = "+product); }
} }
And this is its output:
package javaapplication1;
public class week2q8 {
public static void main(String[] args) {
int i = 0,j,c;
for(j=1;i<=100;i++) {
c=0;
for(j=1;j<i;j++) {
if(i%j==0)
c+=j; }
if(c==i)
System.out.println(i); }
}
}
This is its output:
package javaapplication1;
import java.util.Scanner;
public class Week2Q9 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter any number: ");
int i=s.nextInt();
System.out.println("The value of number in Binary is: "+Integer.toBinaryString(i));
System.out.println("The value of number in Octal is: "+Integer.toOctalString(i));
System.out.println("The value of number in hexadecimal is: "+Integer.toHexString(i));
}
}
And this is its output:
package javaapplication1;
import java.lang.Math;
import java.util.Scanner;
public class Week2Q10 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter the value for coefficient a: ");
double a=s.nextDouble();
System.out.println("Enter the value for coefficient b: ");
double b=s.nextDouble();
System.out.println("Enter the value of constant term c: ");
double c=s.nextDouble();
double d=(Math.pow(b,2)-4*a*c);
double dscr=Math.sqrt(d);
if(d<0){
System.out.println("The given equation has no real roots"); }
else {
double x1=(-b+dscr)/(2*a);
double x2=(-b-dscr)/(2*a);
System.out.println("Roots of the following equation are: "+x1+" and "+x2); }
} }
This is its output:
WEEK 3
WEEK 3
package javaapplication2week3;
import java.util.Scanner;
public class Week3Q1 {
public static void main(String[] args){
double x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter first value: ");
x=s.nextDouble();
System.out.println("Enter the second value: ");
y=s.nextDouble();
System.out.println("The ceil value of x is: "+Math.ceil(x));
System.out.println("The ceil value of y is: "+Math.ceil(y));
#2 Write a program to accept three digits (i.e. 0 - 9) and print all its possible
combinations. (For example, if the three digits are 1, 2, and 3 then all
possible combinations are: 123, 132,213, 231, 312, 321).
package javaapplication2week3;
import java.util.Scanner;
import java.lang.Math;
public class Week3Q2 {
package javaapplication2week3;
public class Week3Q3 {
void area(int b,int h){
System.out.println("The area of triangle is "+((float)0.5*b*h)+" sq units");
}
void area(double x){
System.out.println("The area of square is "+Math.pow(x,2)+" sq units");
}
void area(int r){
double z=3.14*r*r;
System.out.println("The area of the circle is "+z+" sq units");
}
void area(double x,double y){
System.out.println("The area of rectangle is "+x*y+" sq units");
}
}
class overload{
public static void main(String[] args){
Week3Q3 ob=new Week3Q3();
ob.area(14, 7);
ob.area(5);
ob.area(7);
ob.area(16, 14);
} }
BILAL AHMAD 21CAMSA 111 53
LAB COURSE-II | CAMS-20P1
#4 Write a Java Program which prompts the user to enter 4 numbers. The
program will then compute and display their sum and their product.
package javaapplication2week3;
import java.util.Scanner;
public class Week3Q4 {
public static void main(String[] args){
double x,y,z,w,sum,product;
Scanner s=new Scanner(System.in);
System.out.println("Enter first number: ");
x=s.nextDouble();
System.out.println("Enter the second number: ");
y=s.nextDouble();
System.out.println("Enter the third number: ");
z=s.nextDouble();
System.out.println("Enter the fourth number: ");
w=s.nextDouble();
sum=x+y+z+w;
product=x*y*z*w;
System.out.println("Sum of the four numbers entered is: "+sum);
System.out.println("Product of the four numbers entered is: "+product); } }
BILAL AHMAD 21CAMSA 111 54
LAB COURSE-II | CAMS-20P1
#5 Write a Java program which reads a 4-digit number and prints the digits
on separate lines. (Each digit is printed on one line).
package javaapplication2week3;
import java.util.Scanner;
public class Week3Q5 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
int n,TH,H,T,O;
System.out.println("Enter a four digit number: ");
n=s.nextInt();
System.out.println();
TH=n/1000;
System.out.println(TH);
H=(n%1000)/100;
System.out.println(H);
T=((n%1000)%100)/10;
System.out.println(T);
O=(((n%1000)%100)%10);
System.out.println(O);
}
}
package javaapplication2week3;
import java.awt.Rectangle;
import java.util.Scanner;
public class Week3Q6 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter height of first rectangle: ");
BILAL AHMAD 21CAMSA 111 56
LAB COURSE-II | CAMS-20P1
int h1=s.nextInt();
System.out.println("Enter width of first rectangle: ");
int w1=s.nextInt();
System.out.println("Enter x-coordinate of the first rectangle:");
int x1=s.nextInt();
System.out.println("Enter y-coordinate of the first rectangle: ");
int y1=s.nextInt();
System.out.println("Enter height of ssecond rectangle ");
int h2=s.nextInt();
System.out.println("Enter width of second rectangle: ");
int w2=s.nextInt();
System.out.println("Enter x-coordinate of second rectangle: ");
int x2=s.nextInt();
System.out.println("Enter y-coordinate of second rectangle: ");
int y2=s.nextInt();
Rectangle r1=new Rectangle(h1,w1,x1,y1);
System.out.println("First rectangle is: "+r1);
Rectangle r2=new Rectangle(h2,w2,x2,y2);
System.out.println("Second rectangle is: "+r2);
Rectangle r3 = r1.intersection(r2);
System.out.println("Intersecting rectangle is: "+r3);
}
}
package javaapplication2week3;
import java.util.Scanner;
public class Week3Q7 {
public static void main(String[] args){
int even=0,odd=0,evensum=0,oddsum=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter as many numbers as u want : ");
for(int i=1;i>0;i++) {
int n=s.nextInt();
if( n==0){
System.out.println("You have entered a 0. Loop ended.");
break; }
if(n%2==0){
even++;
evensum+=n;
}else{
odd++;
oddsum+=n;
}
}
System.out.println("The number of even integers entered is: "+even+" And the number of odd
integers entered is: "+odd);
System.out.println("Average value of even integers entered is: "+evensum/even);
System.out.println("Average value of odd integers entered is: "+oddsum/odd);
}
}
package javaapplication2week3;
import java.util.Scanner;
public class Week3Q8 {
public static void main(String[] args){
int n1,n2;
Scanner s=new Scanner(System.in);
System.out.println("Enter the upper range: ");
n2=s.nextInt();
System.out.println("Enter the lower range :");
n1=s.nextInt();
System.out.println("Prime numbers between "+n1+" and "+n2+" are given below: ");
int i,j;
for(i=n1;i<n2;i++){
for(j=2;j<i;j++)
{ if(i%j==0)
break;
}
if(j==i)
System.out.print(i+" , ");
}
}} Its output is:
package javaapplication2week3;
import java.util.Scanner;
public class Week3Q9 {
public static void main(String[] args)
{
int n;
System.out.println("Enter the integer whose divisors are to be printed: ");
Scanner s=new Scanner(System.in);
n=s.nextInt();
System.out.println("Divisors of "+n+" are : ");
for(int i=1;i<=n;i++){
if(n%i==0){
System.out.print(i+" , ");
}
}
}
}
package javaapplication2week3;
import java.util.Scanner;
import java.lang.Math;
public class Week3Q10 {
public static void main(String[] args){
int x,n,fact=1;
double sum=0,series;
Scanner s=new Scanner(System.in);
System.out.println("Enter the value for which series is to be printed: ");
x=s.nextInt();
System.out.println("Enter the number of terms for which the series is to be printed: ");
n=s.nextInt();
for(int i=1;i<=n;i++){
fact=fact*i;
sum=sum+(Math.pow(x, i)/fact);
}
series=1-sum;
System.out.println("Sum of the series until "+n+" terms is: "+series);
}}
Its output is:
WEEK 4
WEEK 4
#1 Write Java program involving two classes: OddAndEven &
TestOddAndEven. OddAndEven has the following:
• Instance varaibales countOfOdd and countOfEven both of type int.
• A method addNumber that takes a number as parameter and increment
countOfOdd, if the number is odd, else increment countOfEven.
• A method toString that returns a string in the form: “Number of Odd: x,
Number of Even: y”, where x and y are the values of the instance variables.
The TestOddAndEven class first creates OddAndEven object, then in a
loop,read a number and use it to call the addNumber method until the user
enters Q. Finally, it prints the count of odd and even numbers entered.
package javaapplication3week4;
import java.util.Scanner;
class OddandEven{
int countofEven,countofOdd;
void addNumber(int n){
if(n%2==0){
countofEven++;
}else{
countofOdd++;
}
}
public String toString(){
return"Number of even: "+countofEven+" Number of odd: "+countofOdd;
}
}
public class Q1 {
public static void main(String[] args){
OddandEven o=new OddandEven();
Scanner s=new Scanner(System.in);
for(int i=1;i>0;i++){
System.out.println("Enter any number or q to stop: ");
String b=s.nextLine();
if(b.equals("q")&&!b.equals("Q")){
} else {
break;
}
int a=Integer.parseInt(b);
o.addNumber(a);
}
System.out.println(o);
}
}
And this is its output:
package javaapplication3week4;
import java.lang.Math;
import java.util.Scanner;
public class Week4Q2 {
static class Circle {
int radius;
double x, y;
Circle(int radius, double x, double y) {
this.radius = radius;
this.x = x;
this.y = y;
}
double area() {
double areaCircle = 3.14 * radius * radius;
return areaCircle;
}
double perimeter() {
double perimeterCircle = 2 * 3.14 * radius;
return perimeterCircle;
BILAL AHMAD 21CAMSA 111 66
LAB COURSE-II | CAMS-20P1
}
void checkpoint(double x1, double y1) {
double D = Math.sqrt(Math.pow((x – x1), 2) + Math.pow((y – y1), 2));
if (D < radius) {
System.out.println(“(“ + x1 + “,” + y1 + “) is inside Circle.”);
} else {
System.out.println(“Points are not inside Circle.”);
}
}
public static void main(String[] args){
Scanner obj1 = new Scanner(System.in);
while (true) {
System.out.println(“Enter radius of Circle”);
int rad = obj1.nextInt();
if (rad < 0) {
System.out.println(“Negative radius doesnot exist!!”);
break;
}
System.out.println(“Enter x coordinate of Centre”);
double xCoordinate = obj1.nextDouble();
System.out.println(“Enter y coordinate of Centre”);
double yCoordinate = obj1.nextDouble();
System.out.println(“Enter point to check inside circle or not.”);
System.out.println(“X coordinate”);
double x1 = obj1.nextDouble();
System.out.println(“Y coordinate”);
double y1 = obj1.nextDouble();
Circle obj = new Circle(rad, xCoordinate, yCoordinate);
System.out.println(“Area of Circle = “ + obj.area());
BILAL AHMAD 21CAMSA 111 67
LAB COURSE-II | CAMS-20P1
#3 Write a program in Java that reads in text and prints as output the
following:
• The number of words in the text
• The number of sentences in the text
• The number of times the letter “e” occurs in the text
• The number of times the letter “z” occurs in the text
(Note: Use StringTokenizer class)
package javaapplication3week4;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Week4Q3 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in) ;
System.out.print(" Please enter your Text: " );
String text = sc.nextLine( ) ;
StringTokenizer st = new StringTokenizer(text," ");
/* Prints the number of tokens present in the String */
System.out.println("Number of words in the text is : " + st.countTokens() );
int eCount = 0 ; int zCount = 0 ;
int sentenCount = 0 ;
while (st.hasMoreTokens() ) {
String TokenCheck= st.nextToken() ;
for (int i = 0 ;i< TokenCheck.length() ; i++) {
if (TokenCheck.charAt(i) == 'e')
{ eCount++;}
else if (TokenCheck.charAt(i) == 'z')
{ zCount++; }
else if (TokenCheck.charAt(i) == '.')
{ sentenCount++;
}
else continue;
} }
System.out.println("Number of sentences in the text : " +sentenCount );
System.out.println("Number of times the letter 'e' occurs in the text : " +eCount );
System.out.println("Number of times the letter 'z' occurs in the text : " +zCount ); } }
package javaapplication3week4;
import java.util.Scanner;
class Commission {
public double sale ;
Commission ( double sale ) // constructor
{ this . sale = sale ;
}
public double commission ( double sale ) // method
{ double comm ;
if ( sale < 500 ) {
comm = 2.0*sale/100 ;
}
else if( sale >= 500 && sale < 5000 )
{ comm = 5.0*sale/100 ;
}
else{ // ( sale >= 5000 )
comm = 8.0*sale/100 ;
}
return comm;
}
}
public class Week4q4 {
public static void main (String [ ] args) {
int p ;
Scanner sc = new Scanner( System.in) ;
System.out.print("Please enter your sale : ");
double sale = sc.nextDouble(); Commission obj = new Commission ( sale ) ;
if (sale > 0)
System.out.println("Commision is: " + obj.commission(obj.sale) ) ; // method call
else
System.out.println("Invalid Input”.");
} }
And this is its result:
#5 The certain instructor assigns letter grade for his course based on the
following table:
package javaapplication3week4;
import java.util.Scanner;
class Grader
{
public int score ;
Grader ( int marks)
{ score = marks ;
}
public String letterGrade(int marks )
{ String grade ;
if (marks >= 90 )
grade = "A+";
else if (marks >= 85 )
grade = "A";
else if (marks >= 80 )
grade = "B+";
else if (marks >= 75 )
grade = "B";
else if (marks >= 65 )
grade = "C+";
else if (marks >= 60 )
grade = "C";
else if (marks >= 55 )
grade = "D+";
else if (marks >= 50 )
grade = "D";
else //if (marks < 50 )
grade = "F" ; return grade;
}}
public class Week4Q5 {
public static void main (String [ ] args ) {
Scanner sc = new Scanner (System.in);
System.out.print("Please enter your Score: ");
int marks = sc.nextInt() ;
Grader obj = new Grader(marks);
if (marks > 0 && marks < 100 )
{ System.out.println("Your grade is: " + obj.letterGrade(marks));
}
else
System.out.println("INVALID Input");
}
}
BILAL AHMAD 21CAMSA 111 73
LAB COURSE-II | CAMS-20P1
#6 Create a class named 'Student' with String variable 'name' and integer
variable 'roll_no'. Assign the value of roll_no as '2' and that of name as "John"
bycreating an object of the class Student.
package javaapplication3week4;
import java.util.Scanner ;
class Student {
public String name ;
public int roll_no ;
Student ( int Roll , String name ) {
roll_no = Roll ;
this.name = name ; }
public void Display ( ) {
System.out.println("Name of Student: " + name );
System.out.println("ROll number of Student: " + roll_no );
}}
public class Week4Q6 {
public static void main (String[ ] args ) {
Student obj = new Student(2 , "John");
obj.Display ( ) ;
} }
#7 Write a Java class Clock for dealing with the day time represented by
hours, minutes, and seconds. Your class must have the following features:
Three instance variables for the hours (range 0 - 23), minutes (range 0 -
59),and seconds (range 0 - 59).
Three constructors:
• default (with no parameters passed; is should initialize the represented time
to 12:0:0)
• a constructor with three parameters: hours, minutes, and seconds.
• a constructor with one parameter: the value of time in seconds since
midnight (it should be converted into the time value in hours, minutes,and
seconds)
Instance methods:
• a set-method method setClock() with one parameter seconds since
midnight(to be converted into the time value in hours, minutes, and seconds
as above).
• get-methods getHours(), getMinutes(), getSeconds() with no parameters
that return the corresponding values.
• set-methods setHours(), setMinutes(), setSeconds() with one parameter
each that set up the corresponding instance variables.
• method tick() with no parameters that increments the time stored in a Clock
object by one second.
• method addClock() accepting an object of type Clock as a parameter. The
method should add the time represented by the parameter class to the time
represented in the current class.
• Add an instance method toString() with no parameters to your class.
toString() must return a String representation of the Clock object in the form
"(hh:mm:ss)", for example "(03:02:34)".
package javaapplication3week4;
public class WeekQ7 {
static class Clock{
int hours;
int minutes;
int seconds; //---------- Constructors------------
Clock() {
this.hours = 12;
this.minutes = 0;
this.seconds = 0;
}
Clock(int hours, int minutes, int seconds)
{ this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
Clock(int sec)
{
this.hours = sec / 3600;
sec %= 3600;
this.minutes = sec / 60;
sec %= 60; this.seconds = sec;
}//--------------- Setters ---------------
public void setClock(int sec)
{ this.hours = sec / 3600;
sec %= 3600;
this.minutes = sec / 60;
sec %= 60;
this.seconds = sec;
}
public void setHours(int hours)
{
if(hours > 23)
{ System.out.println("Out of range");
return;}
this.hours = hours;
BILAL AHMAD 21CAMSA 111 77
LAB COURSE-II | CAMS-20P1
}
public void setMinutes(int minutes)
{
if(minutes > 59)
{ System.out.println("Out of range");
return;
}
this.minutes = minutes;
}
public void setSeconds(int seconds)
{
if(seconds > 59){
System.out.println("Out of range");
return;
}
this.seconds = seconds;
}
//-------------Getters------------
public int getHours()
{ return this.hours;
}
public int getMinutes()
{ return this.minutes;
}
public int getSeconds()
{ return this.seconds;
}
//-------------Updaters---------------
BILAL AHMAD 21CAMSA 111 78
LAB COURSE-II | CAMS-20P1
this.seconds += Obj.seconds;
this.minutes += Obj.minutes;
this.hours += Obj.hours;
if(this.seconds >= 60){
this.seconds -= 60;
this.minutes++; }
if(this.minutes >= 60)
{
this.minutes -= 60;
this.hours++;
}
if(this.hours >= 24)
{ this.hours -= 24;
}
}
public void subtractClock(Clock Obj)
{
this.seconds -= Obj.seconds;
this.minutes -= Obj.minutes;
this.hours -= Obj.hours;
if(this.seconds < 0)
{
this.seconds += 60;
this.minutes--;
}
if(this.minutes < 0)
{
this.minutes += 60;
this.hours--;
BILAL AHMAD 21CAMSA 111 80
LAB COURSE-II | CAMS-20P1
}
if(this.hours < 0)
{
this.hours += 24;
}
}
public String toString(){
String hrs = "", min = "", sec="";
if(this.hours < 10)
hrs = "0" + this.hours;
else
hrs += this.hours;
if(this.minutes < 10)
min = "0" + this.minutes;
else
min += this.minutes;
if(this.seconds < 10)
sec = "0" + this.seconds;
else
sec += this.seconds;
return (hrs + ":" + min + ":" + sec);
}
}
//---------End of Clock class -----------
public static void main(String[] args){
Clock firstClock = new Clock(4589);
for (int i = 1; i <= 10; i++) {
firstClock.tick();
System.out.print(firstClock .toString() + " ");
BILAL AHMAD 21CAMSA 111 81
LAB COURSE-II | CAMS-20P1
}
System.out.println();
Clock secondClock = new Clock(23,59,40);
for (int i = 1; i <= 10; i++)
{
secondClock.tick();
System.out.print(secondClock.toString() + " ");
}
System.out.println();
firstClock.addClock(secondClock);
System.out.print("After addition : ");
System.out.println(firstClock.toString());
firstClock.subtractClock(secondClock);
System.out.print("After subtraction : ");
System.out.println(firstClock.toString());
}
}
WEEK 5
WEEK 5
#1 Implement a Student class with the following fields, constructors and
methods:
Fields:
• name;
• totalScore;
• numberOfQuizzes;
Constructors:
• public Student(String name, double score)
• public Student(double score, String name)
• public Student(String name)
Methods:
• public String getName()
• public double getAverage() //this should return zero if no quiz has been
taken.
• public double getTotalScore()
• public void addQuiz(double score)
• public void printStudent() //this should print the student’s name and
average score.
• public String toString()
Write an application TestStudent that reads a student name and use the
Student class to create a Student object. Then read the scores of the student
in three quizzes and add each to the totalScore of the student using
addQuiz() method and print the student object.
( Note: Make use of this key word wherever it can be used ).
package javaapplication4week5;
import java.util.Scanner;
class Student{
String name;
double totalScore;
int numberOfQuizzes;
public Student(String name, double score) {
this.name = name;
totalScore = score;
this.numberOfQuizzes = 1;
}
public Student(double score, String name) {
totalScore = score;
this.name = name;
this.numberOfQuizzes = 1;
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addQuiz(double score) {
totalScore += score;
++this.numberOfQuizzes;
}
public double getAverage() {
if (numberOfQuizzes == 0) {
return 0;
BILAL AHMAD 21CAMSA 111 85
LAB COURSE-II | CAMS-20P1
} else {
return totalScore / numberOfQuizzes;
}
}
public double getTotalScore() {
return totalScore;
}
public void printStudent() {
System.out.println("Name : " + name + "\tAverage is : " +
this.getAverage());
}
@Override
public String toString(){
return name+" "+totalScore+" "+numberOfQuizzes;
}
}
public class Week5Q1 {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.print("Enter name of Student : ");
String name = obj.nextLine();
Student obj1 = new Student(name);
for (int i = 1; i < 4; i++) {
System.out.println("Enter Quiz " + (i) + " for " + name + " : ");
double score = obj.nextDouble();
obj1.addQuiz(score);
}
obj1.printStudent();
} }
BILAL AHMAD 21CAMSA 111 86
LAB COURSE-II | CAMS-20P1
package javaapplication4week5;
import java.util.Scanner;
public class Week5Q2 {
String nameOfDepositor;
int accountNumber;
String typeOfAccount;
BILAL AHMAD 21CAMSA 111 87
LAB COURSE-II | CAMS-20P1
double balance;
void setValues(String name,int accNum,String accType,double balance){
nameOfDepositor = name;
accountNumber = accNum;
typeOfAccount = accType;
this.balance = balance;
}
void deposit(double addMoney){
balance = balance + addMoney;
}
void withdraw(){
Scanner obj = new Scanner(System.in);
System.out.println("Press 1 to Check Balance");
System.out.println("Press 2 to Withdraw Money");
int n = obj.nextInt();
switch(n){
case 1:
System.out.println("Balance : "+balance);
case 2:
System.out.print("Enter amount to withdraw : ");
double withdrawMoney = obj.nextDouble();
if(balance<withdrawMoney){
System.out.println("Insufficient Balance");
}
else{
balance = balance - withdrawMoney;
System.out.println("Withdrawn successfully");
}
}
BILAL AHMAD 21CAMSA 111 88
LAB COURSE-II | CAMS-20P1
}
void display(){
System.out.println("Name : "+nameOfDepositor+"\tBalance : "+balance);
}
public static void main(String[] args){
BankAccount obj = new BankAccount();
obj.setValues("Bilal", 123456, "Savings", 0);
obj.deposit(10000);
obj.withdraw();
obj.display();
}
}
WEEK 6
WEEK 6
#1 Write a program that reads in a sentence from the user and prints it out
with each word reversed, but with the words and punctuation in the original
order.
package javaapplication5week6;
import java.util.Scanner;
import java.util.StringTokenizer;
public class JavaApplication5Week6 {
public static void main(String[] args) {
String temp = "";
System.out.println("Enter a sentence: ");
Scanner obj = new Scanner(System.in);
String str1 = obj.nextLine();
StringTokenizer st = new StringTokenizer(str1," :,!",true);
System.out.print("Output: ");
while(st.hasMoreTokens()){
String str2 = st.nextToken();
String rev1="";
for(int i =str2.length()-1;i>=0;i--) {
rev1 += str2.charAt(i); }
temp+=(rev1); }
System.out.println(temp);
} }
package javaapplication5week6;
interface University{
public void getEnrol();
}
interface Department{
public void facultyNo();
}
class Students implements University,Department{
String enrolNo;
String facNo;
String name;
@Override
public void getEnrol(){
System.out.println(this.name+"'s enrol no = "+this.enrolNo);
}
@Override
public void facultyNo(){
System.out.println(this.name+"'s faculty no= "+this.facNo);
BILAL AHMAD 21CAMSA 111 92
LAB COURSE-II | CAMS-20P1
}
}
public class Week6Q2 {
public static void main(String[] args){
Students s =new Students();
s.name="BILAL";
s.enrolNo="GI1527";
s.facNo="21 CAMSA 111";
s.facultyNo();
s.getEnrol();
}
}
package javaapplication5week6;
import java.util.Scanner;
public class Week6Q3 {
static String[] sortLexo(String[] s1){
BILAL AHMAD 21CAMSA 111 93
LAB COURSE-II | CAMS-20P1
#4 Implement the classes for the shapes using an interface for the common
methods, rather than inheritance from the super class, while still Shape as a
base class.
package javaapplication5week6;
interface Shapes{
int area(int a,int b);
int perimeter(int c, int d);
}
class Rectangle implements Shapes{
public int area(int length,int breadth){
return length*breadth;
}
public int perimeter(int length,int breadth){
return 2*(length+breadth);
}
}
class Square implements Shapes{
public int area(int length,int breadth){
return length*breadth;
}
public int perimeter(int length,int breadth){
return 2*(length+breadth);
}
}
public class Week6Q4 {
public static void main(String[] args){
package javaapplication5week6;
class Person{
String name;
int year;
public Person(){};
public Person(String name,int year){
this.name=name;
this.year=year;
}
@Override
public String toString(){
return name+" "+year;
}
}
class Student extends Person{
String major;
public Student(String major,String name,int year){
super(name,year);
this.major=major;
}
@Override
public String toString(){
return name+" "+year+" "+major;
}
}
class Instructor extends Person{
double salary;
public Instructor(double salary,String name,int year){
super(name,year);
this.salary=salary;
}
@Override
public String toString(){
return name+" "+year+" "+salary;
}
BILAL AHMAD 21CAMSA 111 97
LAB COURSE-II | CAMS-20P1
}
public class Week6Q5 {
public static void main(String[] args){
Student stu = new Student("Computer Science","Bilal",1998);
Instructor ins = new Instructor(20000,"Bilal",1998);
System.out.println(stu);
System.out.println(ins);
}
}
#6 Write a Java class Complex for dealing with complex number. Your class
must have the following features:
• Instance variables :
o realPart for the real part of type double
o imaginaryPart for imaginary part of type double.
• Constructor:
o public Complex (): A default constructor, it should initialize the number to 0,
0)
o public Complex (double realPart, double imaginaryPart): A constructor with
parameters, it creates the complex object by setting the two fields to the
passed values.
• Instance methods:
o public Complex add (Complex otherNumber): This method will find the sum
of the current complex number and the passed complex number. The methods
returns a new Complex number which is the sum of the two.
BILAL AHMAD 21CAMSA 111 98
LAB COURSE-II | CAMS-20P1
o public Complex subtract (Complex otherNumber): This method will find the
difference of the current complex number and the passed complex number.
The methods returns a new Complex number which is the difference of the
two.
o public Complex multiply (Complex otherNumber): This method will find the
product of the current complex number and the passed complex number.
The methods returns a new Complex number which is the product of the two.
o public Complex divide (Complex otherNumber): This method will find the ...
of the current complex number and the passed complex number. The
methods returns a new Complex number which is the ... of the two.
o public void setRealPart (double realPart): Used to set the real part of this
complex number.
o public void setImaginaryPart (double realPart): Used to set the imaginary
part of this complex number.
o public double getRealPart(): This method returns the real part of the
complex number
o public double getImaginaryPart(): This method returns the imaginary part
of the complex number
o public String toString(): This method allows the complex number to be
easily printed out to the screen
Write a separate class ComplexDemo with a main() method and test the
Complex class methods.
package javaapplication5week6;
class Complex{
double realPart;
double imaginaryPart;
public Complex (){
realPart = 0;
imaginaryPart = 0;
}
public Complex (double realPart, double imaginaryPart){
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public Complex add (Complex otherNumber){
Complex num = new Complex();
num.realPart =this.realPart + otherNumber.realPart;
num.imaginaryPart =this.imaginaryPart + otherNumber.imaginaryPart;
return num;
}
public Complex subtract (Complex otherNumber){
Complex num = new Complex();
num.realPart =this.realPart - otherNumber.realPart;
num.imaginaryPart =this.imaginaryPart - otherNumber.imaginaryPart;
return num;
}
public Complex multiply (Complex otherNumber){
Complex num = new Complex();
num.realPart = this.realPart*otherNumber.realPart-
(this.imaginaryPart*otherNumber.imaginaryPart);
num.imaginaryPart =
this.realPart*otherNumber.imaginaryPart+(this.imaginaryPart*otherNumber.realPart);
return num;
}
public Complex divide (Complex otherNumber){
Complex temp = new Complex();
Complex c = new Complex();
double d;
temp.realPart=otherNumber.realPart;
temp.imaginaryPart = -(otherNumber.imaginaryPart);
c=this.multiply(temp);
d=(otherNumber.realPart*otherNumber.realPart) +
(otherNumber.imaginaryPart*otherNumber.imaginaryPart);
System.out.println("d="+d);
if(d==0){
System.out.println("Invalid !!");
}else{
this.realPart = c.realPart/d;
this.imaginaryPart = c.imaginaryPart/d;
}
return this;
}
public void setRealPart (double realPart){
this.realPart = realPart;
}
public void setImaginaryPart (double imaginaryPart){
this.imaginaryPart = imaginaryPart;
}
public double getRealPart(){
return this.realPart;
}
public double getImaginaryPart(){
return this.imaginaryPart;
}
@Override
public String toString(){
return realPart+"+("+imaginaryPart+")i";
BILAL AHMAD 21CAMSA 111 101
LAB COURSE-II | CAMS-20P1
}
}
public class Week6Q6 {
public static void main(String[] args){
Complex com1 = new Complex(3,-2);
System.out.println("Complex number 1 = "+com1);
Complex com2 = new Complex(4,5);
System.out.println("Complex number 2 = "+com2);
Complex com3 = com1.add(com2);
System.out.println("Addition of complex numbers = "+com3);
com3 = com1.subtract(com2);
System.out.println("Subtraction of complex numbers = "+com3);
com3 = com1.multiply(com2);
System.out.println("Multiplication of complex numbers = "+com3);
com3 = com1.divide(com2);
System.out.println("Division of complex numbers = "+com3);
}
}
WEEK 7
WEEK 7
#1 Define a class Employee having private members – id, name, department,
salary. Define default and parameterized constructors. Create a subclass
called “Manager” with private member bonus. Define methods accept and
display in both the classes. Create n objects of the Manager class and
display the details of the manager having the maximum total salary
(salary+bonus).
This is the required code:
package javaapplication6week7;
import java.util.Scanner;
class Employee{
private int id;
private String name;
private String department;
private double salary;
public Employee(){};
public Employee(int id,String name,String department,double salary){
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}
public double getSalary(){
return salary;
}
public void accepts(int id,String name,String department,double salary){
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}
public void display(){
System.out.println("Name : "+name);
System.out.println("ID : "+id);
System.out.println("Department : "+department);
System.out.println("Salary : "+salary);
}
}
class Manager extends Employee{
private double bonus;
public void accepts(int id,String name,String department,double
salary,double bonus){
super.accepts(id, name, department, salary);
this.bonus = bonus;
}
@Override
public void display(){
super.display();
System.out.println("Bonus : "+bonus);
System.out.println("Total Salary : "+(this.getSalary()+bonus));
}
}
public class Week7Q1 {
public static void main(String[] args) {
Manager obj = new Manager();
obj.accepts(213, "Bilal", "IT", 50000, 5000);
BILAL AHMAD 21CAMSA 111 105
LAB COURSE-II | CAMS-20P1
obj.display();
}
}
package javaapplication6week7;
import java.util.Scanner;
class Vehicle{
String Company;
double price;
public Vehicle(){};
public Vehicle(String Company, double price){
this.Company = Company;
this.price = price;
}
}
class LightMotorVehicle extends Vehicle{
String mileage;
public LightMotorVehicle(String Company, double price,String mileage){
super(Company,price);
this.mileage = mileage;
}
}
class HeavyMotorVehicle extends Vehicle{
String capacity;
public HeavyMotorVehicle(String Company, double price,String capacity){
super(Company,price);
this.capacity = capacity;
}
}
public class Week7Q2 {
public static void main(String[] args){
Scanner obj = new Scanner(System.in);
String Company , mileage,capacity;
double price;
for(int i = 0;i<2;i++){
System.out.println("Press 1 for Light Motor Vehicle");
System.out.println("Press 2 for Heavy Motor Vehicle");
int n = obj.nextInt();
switch (n){
case 1:
obj.nextLine();
System.out.print("Enter Vehicle Company : ");
Company = obj.nextLine();
BILAL AHMAD 21CAMSA 111 107
LAB COURSE-II | CAMS-20P1
package javaapplication6week7;
import java.util.Scanner;
class Account {
String cusName;
String typeOfAcc;
long AccNumber;
public Account() {
}
;
public Account(String cusName, String typeOfAcc, long AccNumber) {
this.cusName = cusName;
this.typeOfAcc = typeOfAcc;
this.AccNumber = AccNumber;
}
public void display() {
System.out.println("Name : " + cusName);
System.out.println("Type of account : " + typeOfAcc);
System.out.println("Account Number : " + AccNumber);
}
}
class SavingAccount extends Account {
double balance;
double minBalance = 2000;
public SavingAccount(String cusName, String typeOfAcc, long AccNumber,
double balance) {
super(cusName, typeOfAcc, AccNumber);
this.balance = balance;
}
public void compoundIntrest(int yr, double rate, int n) {
double interest = balance * (Math.pow(1 + rate / (100 * n), n * yr));
balance += interest;
}
public void deposit(double amount) {
balance += amount;
}
public void withdrawl(double amount) {
if (balance >= amount) {
balance -= amount;
if (balance < minBalance) {
System.out.println("Penality of rs 50");
balance -= 50;
}
} else {
System.out.println("Insufficient Balance !!");
}
}
@Override
public void display() {
super.display();
System.out.println("Minimum balance to maintain : rs " + minBalance);
System.out.println("Current balance : " + balance);
}
}
class CurrentAccount extends Account {
double balance;
double minBalance = 2000;
public CurrentAccount(String cusName, String typeOfAcc, long AccNumber,
double balance) {
super(cusName, typeOfAcc, AccNumber);
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdrawl(double amount) {
if (balance >= amount) {
balance -= amount;
if (balance < minBalance) {
System.out.println("Penality of rs 50");
balance -= 50;
}
} else {
System.out.println("Insufficient Balance !!");
}
}
@Override
public void display() {
super.display();
System.out.println("Minimum balance to maintain : rs " + minBalance);
System.out.println("Current balance : " + balance);
}
}
sacc.display();
System.out.print("Enter amount to deposit : ");
double amountDeposit = obj.nextDouble();
sacc.deposit(amountDeposit);
sacc.display();
System.out.print("Enter amount to withdraw :");
double amountWithdraw = obj.nextDouble();
sacc.withdrawl(amountWithdraw);
sacc.display();
} else {
System.out.println("Invalid input!!");
System.out.println("Valid input -> 'Saving' or 'Current'");
}
}
}
package javaapplication6week7;
import java.util.Scanner;
class Fruit {
String nameOfFruit;
int isSingle;
public Fruit(String f, int a) {
this.nameOfFruit = f;
this.isSingle = a;
}
void displayFruit() {
System.out.println("Name of fruit : " + nameOfFruit);
if (isSingle == 1) {
System.out.println("Type of fruit : Single fruit");
} else {
System.out.println("Type of fruit : Bunch fruit");
}
}
}
public class Week7Q4 {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
int n;
String fruit;
for (int i = 0; i < 2; i++) {
System.out.print("Enter name of fruit " + (i + 1) + " : ");
fruit = obj.nextLine();
while (true) {
System.out.println("Press 1 for Single fruit :");
System.out.println("Press 2 for Bunch fruit :");
BILAL AHMAD 21CAMSA 111 117
LAB COURSE-II | CAMS-20P1
n = obj.nextInt();
if (n == 1) {
obj.nextLine();
Fruit single = new Fruit(fruit, n);
single.displayFruit();
break;
} else if (n == 2) {
obj.nextLine();
Fruit bunch = new Fruit(fruit, n);
bunch.displayFruit();
break;
} else {
System.out.println("Invalid input try again!");
}
}
}
}
}
Required code:
package javaapplication6week7;
interface Gps{
void track();
}
interface Camera{
void clickPic();
}
class Phone{
public void call(){
System.out.println("Calling....");
}
}
class SmartPhone extends Phone implements Gps,Camera{
String model;
public SmartPhone(String model){
this.model = model;
}
public String getModel(){
return model;
}
public void track(){
System.out.println("Tracking....");
}
public void clickPic(){
BILAL AHMAD 21CAMSA 111 119
LAB COURSE-II | CAMS-20P1
System.out.println("Clicking picture....");
}
}
public class Week7Q5 {
public static void main(String[] args){
SmartPhone oppo = new SmartPhone("Oppo A83");
System.out.println(oppo.getModel());
oppo.call();
oppo.clickPic();
oppo.track();
}
}
WEEK 8
WEEK 8
#1 Implement the classes for the shapes using an interface for the common
methods, rather than inheritance from the super class, while still Shape as a
base class.
This is the required code:
package javaapplication7week8;
import java.util.Scanner;
interface Shape{
double area();
void print();
}
class Rectangle implements Shape{
double length,width;
public void set(double length,double width){
this.length=length;
this.width=width;
}
public double area(){
return length*width;
}
public void print(){
System.out.println("Area of rectangle is: "+area());
} }
abstract class Circle implements Shape{
double radius;
void set(double radius){
this.radius=radius;
}
public double area(){
return 3.14*radius*radius;
}
public void print(){
System.out.println("The area of Circle is: "+area());
}}
public class JavaApplication7Week8 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the length and breadth of rectangle: ");
double w=sc.nextDouble();
double l=sc.nextDouble();
Rectangle r=new Rectangle();
r.set(w,l);
r.print();
System.out.println("Enter the radius of the circle: ");
double radius=sc.nextDouble();
Circle c=new Circle() {};
c.set(radius);
c.print();
}}
And this is its result:
package arithmetic;
public class ArithmeticWeek8Q2 {
public int add(int x,int y)
{return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
public int mul(int x,int y)
{
return x*y;
}
public double div(int x,int y)
{
return (double)x/y;
}
public int mod(int x,int y)
{
return x%y;
} }
package arithmetic;
import arithmetic.ArithmeticWeek8Q2;
public class Week8Q2 {
public static void main(String as[])
{
ArithmeticWeek8Q2 m=new ArithmeticWeek8Q2();
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
}
}
And this is its result:
package javaapplication7week8;
class Box {
double height,width,depth;
BILAL AHMAD 21CAMSA 111 125
LAB COURSE-II | CAMS-20P1
package javaapplication7week8;
package week_8;
import java.io.FileReader;
import java.io.IOException;
public class Ques_5 {
public static void main(String[] args) {
try{
FileReader file = new FileReader("D:\\hello.txt");
try{
int i, cntWithoutNewLine = 0, cntWithNewLine = 0;
while((i = file.read()) != -1){
char ch = (char) i;
if(ch != '\n' && i != 13) cntWithoutNewLine++;
if(i != 13) cntWithNewLine++;
}
System.out.println("Count with newline character included : " + cntWithNewLine);
System.out.println("Count with newline character excluded : " + cntWithoutNewLine);
}
finally {
System.out.println("Successful Termination");
BILAL AHMAD 21CAMSA 111 128
LAB COURSE-II | CAMS-20P1
file.close();
}
}
catch(IOException e){
System.out.println(e);
}
}
}
And this is its output:
o public double getFirstName(): This method returns the first name of the
author.
o public double getLastName(): This method returns the last name of the
author.
o public String toString(): This method printed out author’s name to the
screen
Write a Java class Book with following features:
• Instance variables :
o title for the title of book of type String.
o author for the author’s name of type String.
o price for the book price of type double.
• Constructor:
o public Book (String title, Author name, double price): A constructor with
parameters, it creates the Author object by setting the the fields to the
passed values.
• Instance methods:
o public void setTitle(String title): Used to set the title of book.
o public void setAuthor(String author): Used to set the name of author of
book.
o public void setPrice(double price): Used to set the price of book.
o public double getTitle(): This method returns the title of book.
o public double getAuthor(): This method returns the author’s name of book.
o public String toString(): This method printed out book’s details to the
screen
Write a separate class BookDemo with a main() method creates a Book titled
“Developing Java Software” with authors Russel Winderand price 79.75.
Prints the Book’s string representation to standard output (using
System.out.println).
package javaapplication7week8;
class Author {
String firstName;
String secondName;
Author() {
}
Author(String firstName, String secondName) {
this.firstName = firstName;
this.secondName = secondName;
}
public void setFirstName(String firstName) {
this.firstName = firstName; }
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public String getFirstName() {
return this.firstName;
}
public String getSecondName() {
return this.secondName;
}
public String tostring() {
return this.firstName + this.secondName;
}
}
class Book extends Author {
String title;
String author_name; // autgor name
double price;
BILAL AHMAD 21CAMSA 111 131
LAB COURSE-II | CAMS-20P1
WEEK 9
WEEK 9
#1 Write a Java program which reads student grades from a text file called
grades.txt and prints only the corresponding letter grades into a file called
letter.txt. The letter grades are assigned according to the following table.
Assume that the grades.txt file can have any number of students’ grades.
Hint: The last number in the grades.txt file is -1.
package javaapplication9week9;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class JavaApplication9Week9 {
public static void main(String[] args) {
File myFile1 = new File("grades.txt");
File myFile2 = new File("letter.txt");
int num;
String grade;
try{
Scanner sc = new Scanner(myFile1);
while(sc.hasNextInt()){
num = sc.nextInt();
if(num>=90){
grade = "A+";
}else if(num>=85){
grade = "A";
}else if(num>=80){
BILAL AHMAD 21CAMSA 111 135
LAB COURSE-II | CAMS-20P1
grade = "B+";
}else if(num>=75){
grade = "B";
}else if(num>=70){
grade = "C+";
}else if(num>=65){
grade = "C";
}else if(num>=60){
grade = "D+";
}else if(num>=55){
grade = "D";
}else{
grade = "F";
}
}
System.out.println(grade);
try{
FileWriter fileWriter = new FileWriter("letter.txt",true);
fileWriter.write(grade + "\n");
fileWriter.close();
}catch(IOException e){
System.out.println(e);
}
}
}
catch(FileNotFoundException e){
System.out.println(e);
}
} }
BILAL AHMAD 21CAMSA 111 136
LAB COURSE-II | CAMS-20P1
#2 Write a program to read a, b, c from data file and store roots of the
quadratic equation in output file. You must open your output file in append
mode.
package javaapplication9week9;
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
public class Week9Q2 {
public static void main(String[] args) {
File myFile = new File("Datafile.txt");
try {
Scanner sc = new Scanner(myFile);
int a = 0, b = 0, c = 0;
double d, r1=0, r2=0;
while (sc.hasNextInt()) {
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
}
d = b * b - 4 * a * c;
if (d >= 0) {
r1 = (-b + d) / (2 * a);
r2 = (-b - d) / (2 * a);
} else {System.out.println("Imaginary roots!!");
}
File myFile1 = new File("Roots.txt");
try{
myFile1.createNewFile();
}catch(IOException e){
System.out.println(e);
}
try{
FileWriter fileWriter = new FileWriter("Roots.txt");
fileWriter.write("First Root = "+r1+"\nSecond Root = "+r2);
fileWriter.close();
}catch(IOException e){
System.out.println(e);
}
try{
Scanner obj = new Scanner (myFile1);
while(obj.hasNextLine()){
String line = obj.nextLine();
System.out.println(line);
}
obj.close();
}catch(FileNotFoundException e){
System.out.println(e);
}
} catch (FileNotFoundException e) {System.out.println(e);
}
}
}
#5 Write a java program to read a file and find total no. of lines in that file.
package javaapplication9week9;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
// e.printStackTrace();
System.out.println(e);
}
}
}
Output:
WEEK 10
WEEK 10
1 - Write applets to draw the following shapes:
a) Cone
SOURCE CODE:
package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_1_b extends Applet {
public void paint(Graphics g){
setBackground(Color.yellow);
g.setColor(Color.black);
g.drawOval(500,60,200,50);
g.drawLine(500,80,500,300);
g.drawLine(700,80,700,300);
g.drawOval(500,280,200,50);
}
}
OUTPUT:
a) Cylinder
SOURCE CODE:
package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_1_b extends Applet {
public void paint(Graphics g){
setBackground(Color.yellow);
g.setColor(Color.black);
g.drawOval(500,60,200,50);
g.drawLine(500,80,500,300);
g.drawLine(700,80,700,300);
g.drawOval(500,280,200,50);
}
}
OUTPUT:
SOURCE CODE:
package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_1_c extends Applet {
public void paint(Graphics g) {
g.setColor(Color.green);
g.drawOval(20, 20, 240, 240);
g.setColor(Color.red);
g.drawRect(65, 60, 150, 150);
}
}
OUTPUT:
#2 Write an applet that will display the following on a green background. Use
the following dimension:
Rectangle : (10, 10, 300, 150), Fill colour: blue
Left Circle : (10, 10, 50, 150), Fill Colour: Yellow
Right Circle: (159, 10, 150, 150), Fill colour: Yellow
Text : (110, 90), colour: Red
SOURCE CODE:
package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_2 extends Applet {
public void paint(Graphics g){
g.setColor(Color.blue);
g.fillRect(10, 10, 300, 150);
g.setColor(Color.yellow);
g.fillOval(10, 10, 150, 150);
g.setColor(Color.yellow);
g.fillOval(150, 10, 150, 150);
g.setColor(Color.red);
g.drawString("RAMADAN MUBARK", 110, 90);
}
}
OUTPUT:
SOURCE CODE:
package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_3 extends Applet {
public void paint(Graphics g){
g.drawOval(10, 10, 240, 180);
g.drawOval(60, 52, 25, 25);
g.drawOval(178, 50, 25, 25);
g.drawLine(63, 130, 198, 130);
}
}
OUTPUT:
WEEK 11
WEEK 11
#1 Write a graphics program that draws a clock face with a time that the user
enters in a text field. (The user must enter the time in the format hh:mm, for
example 09:45).
SOURCE CODE:
package week_11;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Label l;
TextField t;
Button ok,cancel;
double hrs_x = 190, hrs_y = 250, min_x = 120, min_y = 160;
boolean event = false;
add(t);
t.setBounds(20, 50, 200, 30);
add(ok);
ok.setBounds(20, 90, 200, 30);
ok.addActionListener(this);
}
public void paint(Graphics g){
if(event == true){
g.drawOval(20, 150, 200, 200);
g.drawLine(120, 250, (int)min_x, (int)min_y);
g.drawLine(120, 250, (int)hrs_x, (int)hrs_y);
}
}
event = true;
repaint();
}
}
}
SOURCE CODE:
SOURCE CODE:
package week_11;
import java.applet.Applet;
import java.awt.*;
SOURCE CODE:
package week_11;
import java.applet.Applet;
import java.awt.*;
public class Ques_3 extends Applet {
public void paint(Graphics g) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == j) {
g.fillOval(i * 30, j * 30, 20, 20);
} else {
g.drawOval(i * 30, j * 30, 20, 20);
}
}
BILAL AHMAD 21CAMSA 111 153
LAB COURSE-II | CAMS-20P1
}
}
}
SOURCE CODE:
SOURCE CODE:
package week_11;
import java.applet.Applet;
import java.awt.*;
WEEK 12
WEEK 12
#1 Draw a “bull’s eye” a set of concentric rings in alternation black and white
colours: Fill a black circle, and then fill a smaller white circle on top, and so
on.
SOURCE CODE:
package week_12;
import java.applet.Applet;
import java.awt.*;
public class Ques_1 extends Applet {
if (i % 2 != 0) {
g.setColor(Color.black);
g.fillOval(coord, coord, hw, hw);
} else {
g.setColor(Color.white);
g.fillOval(coord, coord, hw, hw);
}
}
BILAL AHMAD 21CAMSA 111 157
LAB COURSE-II | CAMS-20P1
}
}
OUTPUT:
SOURCE CODE:
package week_12;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public Ques_2(){
BILAL AHMAD 21CAMSA 111 158
LAB COURSE-II | CAMS-20P1
f.setSize(400, 300);
f.setLayout(new FlowLayout());
f.setVisible(true);
});
@Override
public void windowClosing(WindowEvent e){
f.dispose();
}
});
}
//Main function
public static void main(String[] args) {
Ques_2 obj = new Ques_2();
}
}
OUTPUT: