Java Lab
Java Lab
PP 1.2: Introduce the following errors, record any error messages that the compiler produces.
PP 1.3: Prints on separate lines, the name of your favorite book, its author, category, price, and total
number of pages.
public class Book
{
public static void main (String[] args)
{
System.out.println("My favorite book\n\tLinear Algebra\nAuthor\n\tGilbert Stang\n"
+"Category\n\tMath\nPrice\n\t$50\n"
+"No.of pages\n\t860\n");
}
}
PP 1.4: Write a program that prints a list of two or three games that you enjoy.
ABDULLAH FAROOQ: 2015-EE-404
PP 1.5: Write a program that prints any two idioms of your choice. Label the priority.
public class Idiom
{
public static void main(String[] agrs)
{
System.out.print("1.Dark Horse\n2.Better Half");
}
}
PP 1.6: Write a program that prints the outline of a house using tilde (~) characters.
PP 1.7: Write a program that prints one of your favorite phrase and its meaning.
PP 1.10: Write a program that displays the word “HI” in large block letters.
public class HI
{
public static void main (String[] args)
{
System.out.println("I I I III H H H H H H H H H H\n"+
"I I I III H\n"+
"I I I III H\n"+
"I I I III H\n"+
"I I I I I I I I I I I I I I I H\n"+
"I I I III H\n"+
"I I I III H\n"+
"I I I III H\n"+
"I I I III H H H H H H H H H H\n");
}
}
PP 2.1: Print the Lincoln program, the quotation inside a box made up of character ^.
ABDULLAH FAROOQ: 2015-EE-404
PP 2.2: Write a program that reads four integers and prints the sum of their squares.
import java.util.Scanner;
public class SquareIntegers
{
public static void main (String[] args)
{
int a, b, c, d, sum;
a=a*a;
b=b*b;
c=c*c;
d=d*d;
sum= a+b+c+d;
System.out.println("sum=" +sum);
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 2.3: Write a program that reads three floating point numbers and prints the cube of their average.
import java.util.Scanner;
public class CubeofAverage
{
public static void main (String[] args)
{
float a, b, c, cube, avg;
a=scan.nextFloat();
b=scan.nextFloat();
c=scan.nextFloat();
avg= (a+b+c)/3;
cube= avg*avg*avg;
PP 2.4: Write a program that prompts for and reads a course name, its credits and reference book.
Then print the following paragraph, inserting the appropriate data:
import java.util.Scanner;
public class NewSemester
{
public static void main (String[] args)
{
String course, credits, reference_book;
System.out.println("Enter Data");
course= scan.nextLine();
credits= scan.nextLine();
reference_book= scan.nextLine();
System.out.println("This semester, a new course on "+ course+ " has been addedto the
curriculum.\n"+
"It consists of "+ credits+ " credits and the reference book for this\ncourse is "+
reference_book+ ".");
}
}
PP 2.5: Create a version of the UnitConverter application to convert from inches to foot. Read the
inches value from the user.
import java.util.Scanner;
public class UnitConverter
{
public static void main (String[] args)
{
float inch, foot;
System.out.println("Enter Value");
inch= scan.nextFloat();
foot= inch/12;
PP 2.6: Write a program that converts grams to pounds. (One pound equals 453.592 grams.) Read the
grams value from the user as a floating point value.
import java.util.Scanner;
public class UnitConverter1
{
public static void main (String[] args)
{
double grams, pounds;
System.out.println("Enter Value");
grams= scan.nextDouble();
pounds= grams/453.592;
PP 2.7: Write a program that prompts for and reads integer values for typing speed and number of
characters in the document, then prints the time required to type them as a floating point result.
import java.util.Scanner;
public class Typing_Speed
{
public static void main(String[] args)
{
int typspd, chrctr;
float time;
System.out.println("Time required to type "+ chrctr+ " characters = "+ time+ " second");
}
}
PP 2.8: Write a program that reads values representing the weight in kilograms, grams, and
milligrams and then prints the equivalent weight in milligrams.
import java.util.Scanner;
kg= scan.nextInt();
grm= scan.nextInt();
mg= scan.nextInt();
ABDULLAH FAROOQ: 2015-EE-404
eqlnt= kg*1000+grm;
eqlnt1= eqlnt*1000+mg;
System.out.println(kg+ " kg, "+ grm+ " grm and "+ mg+ " mg = "+ eqlnt1+ " miligrams");
}
}
PP 2.9: Create a version of the previous project that reverses the computation.
import java.util.Scanner;
mg= scan.nextLong();
original= mg;
kg= mg/1000000;
mg= mg%1000000;
grm= mg/1000;
mg= mg%1000;
System.out.println(original+ " mg = "+ kg+ " kg "+ grm+ " grm "+ mg+ " mg");
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 2.10: Write a program that determines the value of the coins in a jar and prints the total in dollars
and cents. Read integer values that represent the number of quarters, dimes, nickels, and pennies.
import java.util.Scanner;
System.out.println("Enter the no. of coins of quarters, dimes, nickels and pennies respectively.");
qt= scan.nextInt();
dm= scan.nextInt();
nk= scan.nextInt();
pn= scan.nextInt();
eq1= qt*25;
eq2= dm*10;
eq3= nk*5;
eq4= pn*1;
cn= eq1+eq2+eq3+eq4;
dlr= cn/100;
cn= cn%100;
System.out.println("The total value of coins in jar = "+ dlr+ " dollars "+ cn+ " cents");
}
}
PP 2.11: Write a program that prompts for and reads a double value representing a monetary
amount. Then determine the fewest number of each bill and coin needed to represent that amount,
starting with the highest (assume that a ten-dollar bill is the maximum size needed).
import java.util.Scanner;
{
public static void main(String[] args)
{
int ten, five, one=0, q, d, n, p, eqv; //one initialized for loop.
double amt, rpt, eqv1;
eqv= eqv%10;
five= eqv/5; //five dollars bills
if(eqv>5)
one= eqv-5; //one dollar bills
if(five<=0)
one= eqv;
amt= amt*100;
eqv1= amt%100;
PP 2.12: Write a program that prompts for and reads two integers representing the length and
breadth of a rectangle, then prints its perimeter and area.
import java.util.Scanner;
l= scan.nextInt();
w= scan.nextInt();
p= 2*(l+w);
a= l*w;
PP 2.13: Write a program that prompts for and reads the circumference of a circle as a floating point
value (double), then prints the radius of the circle.
import java.util.Scanner;
circum= scan.nextDouble();
radius= circum/(2*3.141592654);
PP 3.1: Write a program that prompts for and reads the user’s city and country (separately). Then
print a string composed of the first two letters of the user’s country, followed by a comma and then
followed by user’s city, followed by a random number in the range 1 to 100 which represents the pin
code of the city.
import java.util.Scanner;
import java.util.Random;
public class PP3_1
{
public static void main(String[] args)
{
Scanner scan=new Scanner (System.in);
System.out.println("First Enter your City and then Country");
String city, country, name;
city=scan.nextLine();
country=scan.nextLine();
int pin;
pin=gen.nextInt(100)+1;
System.out.println("PIN Code "+pin);
name=country.substring(0,2);
System.out.println(name+", "+city+" "+pin);
}
}
PP 3.2: Write a program that prints the square of the product. Prompt for and read three integer
values and print the square of the product of all the three integers.
import java.util.Scanner;
{
int a,b,c,pro,sq;
a=scan.nextInt();
b=scan.nextInt();
c=scan.nextInt();
pro=a*b*c;
sq= (int) Math.pow(pro, 2);
PP 3.3: Write a program that creates and prints a random phone number of the form XXX–XXX–XXXX.
import java.util.Random;
public class PP3_3
{
public static void main(String[]args)
{
Random rand=new Random();
int a,b,c,d,f;
a=rand.nextInt(8);
b=rand.nextInt(8);
c=rand.nextInt(8);
d=rand.nextInt(555)+100;
f=rand.nextInt(9000)+1000;
System.out.println("Requirred phone number is\n" +a+b+c+"-"+d+"-"+f);
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 3.4: Write a program that reads an integer value and prints the value e raised to the power of that
number.
import java.util.Scanner;
PP 3.5: Write a program that reads the (x, y) coordinates for two points which form a straight line.
Compute the slope of the line.
import java.util.Scanner;
double slope;
slope= (double) (y2-y1)/(x2-x1);
ABDULLAH FAROOQ: 2015-EE-404
PP 3.6: Write a program that reads the radius of a sphere and prints its volume and surface area. Use
the following formulas. Print the output to four decimal places.
import java.util.Scanner;
import java.text.DecimalFormat;
public class PP3_6
{
public static void main(String[]args)
{
Scanner scan= new Scanner(System.in);
DecimalFormat fmt= new DecimalFormat("0.####");
double radius,volume,area;
final double VBASE = 4.186667;
final double ABASE = 12.56;
System.out.println("Enter radius of sphere");
radius=scan.nextDouble();
volume=VBASE*radius*radius*radius;
area=ABASE*radius*radius;
System.out.println("Volume of sphere is : "+ fmt.format(volume));
System.out.println("Surface Area of sphere is : "+ fmt.format(area));
}
}
PP 3.7: Write a program that reads the two sides and the height of a trapezoid from the user.
Compute the area of the trapezoid.
ABDULLAH FAROOQ: 2015-EE-404
import java.util.Scanner;
import java.text.DecimalFormat;
public class PP3_7
{
public static void main(String[]args)
{
Scanner scan= new Scanner(System.in);
DecimalFormat fmt= new DecimalFormat("0.##");
double area,a,b,h;
final double BASE=0.5;
System.out.println("Enter two sides of trapezoid");
a=scan.nextDouble();
b=scan.nextDouble();
System.out.println("Enter height of trapezoid");
h=scan.nextDouble();
area=BASE*h*(a+b);
System.out.println("Area of trapezoid is :"+ fmt.format(area));
}
}
PP 3.8: Write a program that generates two random integers in the range 1 to 20, inclusive, and
displays the sine and cosine of the sum of those two integers.
import java.util.Random;
public class PP3_8
{
public static void main(String[]args)
{
Random rand=new Random();
int a,b,sum;
double sine ,cosine;
a=rand.nextInt(20)+1;
b=rand.nextInt(20)+1;
sum= a+b;
sine=Math.sin(sum);
ABDULLAH FAROOQ: 2015-EE-404
cosine=Math.cos(sum);
System.out.println("Sine of sum of two random numbers is: "+sine);
System.out.println("Cosine of sum of two random numbers is: "+cosine);
}
}
PP 3.9: Write a program that generates a random integer base (b), height (h) and a side (a) for a
parallelogram in the range 10 to 30, inclusive, and then computes the area and perimeter of the
parallelogram.
import java.util.Random;
public class PP3_9
{
public static void main(String[]args)
{
Random rand=new Random();
int a,b,h;
double area,perimeter;
final int BASE=2;
a=rand.nextInt(20)+10;
b=rand.nextInt(20)+10;
h=rand.nextInt(20)+10;
area=b*h;
perimeter=BASE*(a+b);
System.out.println("Area of parallalogram is :"+area);
System.out.println("Perimeter of parallalogram is :"+perimeter);
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 4.1: Write a class called NumberOfGoals that represents the total number of goals scored by a
football team. Create a driver class called GoalTracker that creates a few NumberOfGoals objects and
tests their methods.
Coding of Class
public class NumberOfGoals
{
private int goals; //instance data
public NumberOfGoals()
{
//constructor
goals=0;
}
public void setGoal()
{
//to set goals
goals++;
}
public int getGoal()
{
// check goals
return goals;
}
public String toString()
{
String result=Integer.toString(goals);
return result;
}
}
Driver Class
public class GoalTracker
{
public static void main(String[]args)
{
NumberOfGoals teamAgoals,teamBgoals;
int sum;
teamAgoals=new NumberOfGoals();
teamBgoals=new NumberOfGoals();
teamAgoals.setGoal();
teamBgoals.setGoal();
teamAgoals.setGoal();
System.out.println(" Team A goals: "+teamAgoals+"\n Team B goals: "+teamBgoals);
sum=teamAgoals.getGoal()+teamBgoals.getGoal();
System.out.println("Total num of Goals: " +sum);
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 4.2: Write a class called BitValue that represents binary digits that can be set to true or false.
Create a driver class called Bits whose main method instantiates and sets a few bits to true.
Class
public class BitValue
{
private int value;
bit2.setValue(1);
ABDULLAH FAROOQ: 2015-EE-404
num1 = bit1.getValue();
num2 = bit2.getValue();
PP 4.3: Write a class called Circle that contains instance data that represents the circle’s radius. Create
a driver class called MultiCircle, whose main method instantiates and updates several Circle objects.
Class
public class Circle
{
private float radius;
private float area =0f;
private float circum =0f;
public Circle()
{
radius=3.5f;
}
public void setterRadius(float x)
{
radius=x;
}
public float getterRadius()
{
return radius;
}
public float area()
{
area=(float)Math.PI*radius*radius;
return area;
}
public float circum()
{
circum=(float)Math.PI*radius *2;
return circum;
}
public String toString()
{
String statement="The circle of radius "+radius+" has area "+area+" and it circumference is "+circum;
ABDULLAH FAROOQ: 2015-EE-404
return statement;
}
}
Driver Class
public class MultiCircle
{
public static void main(String[] args)
{
Circle r1,r2;
r1= new Circle();
r2= new Circle();
r2.setterRadius(2.5f);
r1.area();
r1.circum();
r2.area();
r2.circum();
System.out.println(r1);
System.out.println(r2);
}
}
PP 4.4: Write a class called Dog that contains instance data that represents the dog’s name and age.
Create a driver class called Kennel, whose main method instantiates and updates several Dog objects.
Class
public class Dog
{
private String name;
private int age;
int personyear;
public Dog(String s,int a)
{
name=s;
age=a;
}
public void setname(String s1)
{
name=s1;
}
public void setage(int b)
{
age=b;
}
public String getname()
ABDULLAH FAROOQ: 2015-EE-404
{
return name;
}
public int getage()
{
return age;
}
public int modifyage()
{
personyear=7*age;
return personyear;
}
public String toString()
{
return (name+" \t "+age+" \t "+personyear);
}
}
Driver Class
public class Kennel
{
public static void main(String[]args)
{
Dog d1,d2;
int a;
d1=new Dog("Tommi",10);
d2=new Dog("Muddi",8);
d2.setname("Nehro");
d1.setage(6);
a=d2.modifyage();
System.out.println(d1.getname());
System.out.println("dog2 age is "+a);
d1.modifyage();
System.out.println("Name\t Age \t Personyears");
System.out.println(d1);
System.out.println(d2);
}
}
PP 4.5: Write a class called Phone that contains instance data that represents the make, model, and
year of the phone. Create a driver class called PhoneCheck, whose main method instantiates and
updates several Phone objects.
ABDULLAH FAROOQ: 2015-EE-404
Class
public class Phone
{
private String make,modle;
private int year;
boolean state;
public Phone()
{
make="Nokia";
modle="215";
year=2016;
}
public void setmake(String s1)
{
make=s1;
}
public void setmodle(String s2)
{
modle=s2;
}
public void setyear(int a)
{
year=a;
}
public String getmake()
{
return make;
}
public String getmodle()
{
return modle;
}
public int getyear()
{
return year;
}
public Boolean isobsolete()
{
if((2016-year)>10)
{
state=true;
return state;
}
else
{
state=false;
return state;
ABDULLAH FAROOQ: 2015-EE-404
}
}
public String toString()
{
return(make+" \t "+modle+" \t "+year+" \t "+state);
}
}
Driver Class
public class PhoneCheck
{
public static void main(String[]args)
{
Phone p1,p2;
p1=new Phone();
p2=new Phone();
p2.setmake("QMobile");
p2.setmodle("S2");
p1.setyear(2015);
System.out.println(p1.getmake());
System.out.println(p2.getyear());
p1.isobsolete();
p2.isobsolete();
System.out.println("Make \t Modle \t Year \t Obsolete");
System.out.println(p1);
System.out.println(p2);
}
}
PP 4.6: Write a class called Shelf that contains instance data that represents the length, breadth, and
capacity of the shelf. Create a driver class called ShelfCheck, whose main method instantiates and
updates several Shelf objects.
Class
public class Shelf
{
private double length,breadth;
private int capacity;
private Boolean occupied;
public Shelf(double a,double b,int c)
{
length=a;
ABDULLAH FAROOQ: 2015-EE-404
breadth=b;
capacity=c;
occupied=false;
}
public void setlength(double d)
{
length=d;
}
public void setwidth(double e)
{
breadth=e;
}
public void setcapacity(int f)
{
capacity=f;
}
public void setoccupied(Boolean g)
{
occupied=g;
}
public double getlength()
{
return length;
}
public double getwidth()
{
return breadth;
}
public int getcapacity()
{
return capacity;
}
public Boolean isoccupied()
{
return occupied;
}
public String toString()
{
return(length+" \t "+breadth+" \t "+capacity+" \t "+occupied);
}
}
Driver Class
public class ShelfCheck
{
public static void main(String[]args)
{
Shelf s1,s2;
s1=new Shelf(7.5,2.5,50);
ABDULLAH FAROOQ: 2015-EE-404
s2=new Shelf(5.5,1.5,20);
s1.setlength(7.3);
s2.setwidth(2.9);
s1.setoccupied(true);
s2.setcapacity(25);
System.out.println("TOtal Capacity: "+(s1.getcapacity()+s2.getcapacity()));
System.out.println("Length \t Width \t Capacity \t Occupied");
System.out.println(s1);
System.out.println(s2);
}
}
PP 4.7: Write a class called Laptop that contains instance data for the laptop model, make, purchaser,
and purchase year. Create a driver class called LaptopRecords whose main method instantiates and
updates several Laptop objects.
Class
public class Laptop
{
private String make,model,perchaser;
private int perchaseyear;
public Laptop(String s1,String s2,String s3,int a)
{
make=s1;
model=s2;
perchaser=s3;
perchaseyear=a;
}
public void setdata(String s4,String s5,String s6,int b)
{ //seter method for each instent data can be defined individually
make=s4;
model=s5;
perchaser=s6;
perchaseyear=b;
}
public String getmake()
{ //getter method must be defined indiviidually because it return only one value
return make;
}
public String getmodel()
{
return (model +" "+ make);
ABDULLAH FAROOQ: 2015-EE-404
}
public String getperchaser()
{
return perchaser;
}
public int getyear()
{
return perchaseyear;
}
public String toString()
{
return("Make\t :"+make+"\nModel\t :"+model+"\nPerchaser :"
+perchaser+"\nPerchaseyear :"+perchaseyear);
}
}
Driver Class
public class LaptopRecord
{
public static void main(String[]args)
{
Laptop pc1=new Laptop("Dell","Core i3","Junaid-ur-Rehman",2013); //object can also be declared
as
Laptop pc2=new Laptop("Hp","Core i3","Junaid-ur-Rehman",2016);
pc2.setdata("Hp","core i5","Ahmad",2015);
System.out.println("Make : "+pc1.getmake()+", Model : "+pc1.getmodel());
System.out.println(pc2);
}
}
PP 4.8: Write a class called Course that represents a course offered to students. Create a driver class
called CourseDetails whose main method instantiates and updates several Course objects.
Class
public class Course
{
private String title,code,name;
private int credit;
public Course(String s1,String s2,int a,String s3)
{
title=s1;
code=s2;
credit=a;
ABDULLAH FAROOQ: 2015-EE-404
name=s3;
}
public void setdata(String s4,String s5,int b,String s6)
{
title=s4;
code=s5;
credit=b;
name=s6;
}
public String getdata()
{ //altenate method but for only String return type for others individually
return(title+"\t"+code+"\t"+credit+"\t"+name);
}
public String toString()
{
return(title+"\t"+code+"\t"+credit+"\t"+name);
}
}
Driver Class
public class CourseDetails
{
public static void main(String[]args)
{
Course c1=new Course("Introduction to computing","CS-141",3,"Haseeb");
Course c2=new Course("Programming Funtamentals","EE-230",3,"M.Yasir");
c1.setdata("Introduction to computing","CS-141L",1,"Haseeb");
System.out.println("Title \t\t\tCode\tCredit\tInstructor");
System.out.println(c1.getdata());
System.out.println(c2);
}
}
PP 4.9: Write a class called PairOfDice, composed of two Die objects. Create a driver class called
RollingDice2 to instantiate and use a PairOfDice object.
Class
public class PairofDice
{
private final int MAX =6;
private int facevalue1,facevalue2,sum;
public PairofDice()
{ //constructor
facevalue1=1;
ABDULLAH FAROOQ: 2015-EE-404
facevalue2=1;
sum=2;
}
public int setDice1(int a)
{ //setter
facevalue1=a;
return facevalue1;
}
public int setDice2(int b)
{
facevalue2=b;
return facevalue2;
}
public int getDice1()
{ //getter
return facevalue1;
}
public int getDice2()
{
return facevalue2;
}
public int rollA()
{
facevalue1=(int)(Math.random()*MAX)+1;
return facevalue1;
}
public int rollB()
{
facevalue2=(int)(Math.random()*MAX)+1;
return facevalue2;
}
public void Sum(int c,int d)
{ //sum of current values
sum=c+d;
}
public String toString()
{
String result=Integer.toString(sum);
return result;
}
}
Driver Class
public class Rollingice2
{
public static void main(String[]args)
{
PairofDice die1,die2,adder;
int value1,value2;
ABDULLAH FAROOQ: 2015-EE-404
die1=new PairofDice();
die2=new PairofDice();
adder=new PairofDice();
value1=die1.rollA();
value2=die2.rollB();
adder.Sum(value1,value2);
System.out.println(" Die one :" +value1+" Die Two :" +value2);
System.out.println(" Sum :" +adder);
value1=die1.setDice1(5);
value2=die2.setDice2(3);
adder.Sum(value1,value2);
System.out.print (" Die one :"+die1.getDice1());
System.out.println(" Die Two :"+die2.getDice2());
System.out.println(" Sum :" +adder);
}
}
PP 5.1: Write a program that reads an integer value from the user representing a year. Produce an
error message for any input value less than 1582 (the year the Gregorian calendar was adopted). AND
PP 5.2: Modify the solution to the previous project 5.1 so that the user can evaluate multiple years.
Allow the user to terminate the program using an appropriate sentinel value.
ABDULLAH FAROOQ: 2015-EE-404
import java.util.Scanner;
public class PP5_1
{
public static void main(String[]args)
{
int LY; // Leap Year
String another = "Y";
final int MIN = 1582;
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
PP 5.3: Write a program that calculates and prints, the sum and product of all the digits in an integer
value read from the keyboard.
import java.util.Scanner;
public class PP5_3
{
public static void main(String[]args)
{
int num;
int sum=0 , prod = 1;
Scanner input = new Scanner(System.in);
System.out.println(" Enter Number( zero to quit ) : " );
num = input.nextInt();
while(num!=0) //sentinal-value
{
sum += num;
prod*=num;
System.out.println(" Enter Number( zero to quit ) : " );
num = input.nextInt();
}
System.out.println("Sum is : " +sum);
System.out.println("product is : " +prod);
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 5.4: Write a program that plays the Hi-Lo guessing game with numbers. The program should pick a
random number between 1 and 100 (inclusive), then repeatedly prompt the user to guess the
number.
import java.util.*;
public class PP5_4
{
public static void main(String[]args)
{
int num , guess,c=0,d=0;
String another = "Y";
Random generator = new Random();
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
while(another.equalsIgnoreCase("Y"))
{
num = generator.nextInt(99)+1;
System.out.println("Guess, what is number between "+ 1 + " to " +100);
guess = scan.nextInt();
if(guess==num)
{
System.out.println(" You got it.. You are Genius..!!");
System.out.println("Number was " + num);
c++;
}
else
{
System.out.println("Wrong...Better Luck..!!");
System.out.println("Number was " + num);
d++;
}
System.out.println("Do You want to play once more?? (y/n) ?");
another = input.nextLine();
}
System.out.println(" Right-Guesses= " + c + " Wrong-Guesses= " + d);
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 5.5: Create a ChangeCase program which considers a string as an input from the user and identifies
whether the characters of the string are in uppercase or lowercase, then changes all the lowercase
characters, if any, to uppercase and vice versa.
import java.util.Scanner;
public class PP5_5
{
public static void main(String[]args)
{
Scanner scan =new Scanner(System.in);
String s,s1,s2;
System.out.println("Enter String " );
s=scan.nextLine();
s1=s.toUpperCase();
s2=s.toLowerCase();
System.out.println(" String in Upper-case is : " + s1);
System.out.println(" String in Lower-Case is : " + s2);
}
}
PP 5.7: Write a program that plays the Rock-Paper-Scissors game against the computer. When played
between two people, each person picks one of three options (usually shown by a hand gesture) at the
same time, and a winner is determined.
import java.util.*;
import java.util.ArrayList;
public class PP5_7
{
public static void main(String[]args)
{
ArrayList<String> possibility = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Random generator = new Random();
final int MAX = 3;
String another = "Y";
int select,guess1,guess2;
possibility.add("Rock beats Scissor");
possibility.add("Scissor beats Paper");
possibility.add("Paper beats Rock");
System.out.println(possibility);
ABDULLAH FAROOQ: 2015-EE-404
PP 5.8: Design and implement an application that simulates an odd slot machine in which five
numbers between 1 and 100 are randomly selected and printed side by side. Print an appropriate
statement if all five of the numbers are odd, or if any one of the numbers is odd. Continue simulating
until the user chooses to stop.
import java.util.*;
public class PP5_8
{
public static void main(String[]args)
{
int n1 ,n2 ,n3, n4, n5;
String another="Y";
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Random generator = new Random();
ABDULLAH FAROOQ: 2015-EE-404
while(another.equalsIgnoreCase("Y"))
{
n1=generator.nextInt(100)+1;
n2=generator.nextInt(100)+1;
n3=generator.nextInt(100)+1;
n4=generator.nextInt(100)+1;
n5=generator.nextInt(100)+1;
System.out.println("Number which are Randomly choosed are given below...");
System.out.println("Number 1 : " + n1 + "\tNumber 2 : " + n2 + "\tNumber 3 :" +
n3 + "\tNumber 4 : " +n4 + "\tNumber 5 : " + n5);
if(n1 % 2!=0)
System.out.print(" "+ n1);
if(n2 % 2!=0)
System.out.print(" " + n2);
if(n3 % 2!=0)
System.out.print(" " + n3);
if(n4 % 2!=0)
System.out.print(" " + n4);
if(n5 % 2!=0)
System.out.print(" " + n5);
System.out.println();
System.out.println("Do you want play more (Y/N)");
another=input.nextLine();
}
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 6.1: Write a program that reads an integer value and prints the average of all odd integers between
0 and the input value, inclusive. Print an error message if the input value is less than 0. Prompt
accordingly.
import java.util.Scanner;
public class PP6_1
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int a, n, ave, sum=0, d=0;
System.out.println("Enter upper limit to" +
" get average of \"Odd-Num\": ");
a=scan.nextInt();
if(a>0)
{
for(n=0; n<=a; n++)
{
if(n%2 != 0)
{
sum+=n;
d++;
}
}
System.out.println(" Sum is : "+ sum);
System.out.println(" No of counter is " + d);
ave = sum/d;
System.out.println(" Average is : " + ave);
}
else
System.out.println("Invalid Number...");
}
}
PP 6.2: Write a program that reads a string from the user and prints it one character per line.
import java.util.Scanner;
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
String s;
int i, a;
System.out.println("Enter a String ...");
s= scan.nextLine();
a= s.length();
for(i=0;i<a;i++)
{
System.out.println(" " + s.charAt(i));
}
}
}
PP 6.3: Write a program that produces a table of random workload assignments, representing the
workload assigned to 10 employees on every weekday.
import java.util.ArrayList;
import java.util.Random;
public class PP6_3
{
public static void main(String[]args)
{
Random generator = new Random();
int i, j;
ArrayList<String> a1 = new ArrayList<String>();
ArrayList<String> a2 = new ArrayList<String>();
ArrayList<String> a3 = new ArrayList<String>();
a1.add("Ali");
a1.add("Ahamd");
a1.add("Bilal");
a1.add("Junaid");
a1.add("Inam");
a1.add("Manan");
a1.add("Zaheer");
ABDULLAH FAROOQ: 2015-EE-404
a1.add("aqib");
a1.add("Sheikh");
a1.add("Hassan");
System.out.println(a1);
a2.add("sweeping");
a2.add("cooking");
a2.add("guarding");
a2.add("Managing");
a2.add("driving");
a2.add("packing");
a2.add("binding");
a2.add("collecting");
a2.add("stitching");
a2.add("as servant");
System.out.println(a2);
a3.add("Monday");
a3.add("Tuesday");
a3.add("Wednesday");
a3.add("Thursday");
a3.add("Friday");
a3.add("Saturday");
a3.add("Sunday");
for(i=1;i<8;i++)
{
System.out.println();
if(i%i == 0)
{
System.out.println(" On " + a3.get(i-1) + " : ");
System.out.println();
for(j=0;j<10;j++)
{
int c =generator.nextInt(10);
String d=a2.get(c);
System.out.println("work is done by : "+ a1.get(j)+ "\t" + "----> " + d);
}
}
}
}
}
ABDULLAH FAROOQ: 2015-EE-404
OUTPUT continues…
PP 6.4: Write a program that prints the first few verses of the traveling song “One Hundred Bottles of
Beer.” Use a loop such that each iteration prints one verse. Read the number of verses to print from
the user. Validate the input.
import java.util.Scanner;
public class PP6_4
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
int n;
String another = "Y";
while(another.equalsIgnoreCase("Y"))
{
System.out.println("Enter Number to print that Verse");
n=scan.nextInt();
if(n>0 && n<=100)
{
System.out.print( n +" Bottles of beer on the wall" + "\n" +
ABDULLAH FAROOQ: 2015-EE-404
System.out.println("\n");
System.out.println("Dou Want to print more. (Y/N) ?? ");
another=input.nextLine();
}
}
}
PP 6.5: Using the PairOfDice class from PP 4.9, write a program that rolls a pair of dice 1000 times,
counting the number of box cars (two sixes) that occur.
PairOfDice:
public class PP6_5i
{
private final int MAX =6;
private int facevalue1, facevalue2, sum, a, b, c=0;
public PP6_5i()
{ //constructor
facevalue1=1;
facevalue2=1;
sum=2;
}
public int rollA()
{
facevalue1= (int) (Math.random()*MAX)+1;
return facevalue1;
}
public int rollB()
{
facevalue2= (int) (Math.random()*MAX)+1;
return facevalue2;
ABDULLAH FAROOQ: 2015-EE-404
}
public int BoxCars()
{
for(int i=1; i<=1000; i++)
{
a=rollA();
b=rollB();
if(a==6 && b==6)
c+=1;
}
return c;
}
public String toString()
{
String result=Integer.toString(facevalue1);
return result;
}
}
Driver Class:
public class PP6_5ii
{
public static void main(String[]args)
{
PP6_5i die = new PP6_5i();
int value;
value=die.BoxCars();
PP 6.6: Using the Person class from Chapter 5, write a program called SelectPerson whose main
method selects a person 25 times and counts how many times each gender is selected. Print
the results.
Class:
public class Person
{
private final int FEMALE = 0;
ABDULLAH FAROOQ: 2015-EE-404
public Person()
{
shuffle();
}
public int shuffle()
{
person = (int) (Math.random() * 2);
return person;
}
public int getValue()
{
return person;
}
public String toString()
{
String perName;
PP 6.7: Create modified versions of the Stars program to print the following patterns. Create a
separate program to produce each pattern.
Part a:
public class PP6_7a
{
public static void main(String[] args)
{
int i=10;
for(int j=1;j<=10;j++)
{
for(int k=1;k<=i;k++)
System.out.print("*");
System.out.println();
i--;
}
}
}
Part b:
public class PP6_7b
{
public static void main(String[] args)
{
int i=9,n=1;
for(int j=1;j<=10;j++)
{
for(int k=1;k<=i;k++)
System.out.print(" ");
ABDULLAH FAROOQ: 2015-EE-404
for(int m=1;m<=n;m++)
System.out.print("*");
System.out.println();
i--;
n++;
}
}
}
Part c:
public class PP6_7c
{
public static void main(String[] args)
{
int i=0,n=10;
for(int j=1;j<=10;j++)
{
for(int k=1;k<=i;k++)
System.out.print(" ");
for(int m=1;m<=n;m++)
System.out.print("*");
System.out.println();
i++;
n--;
}
}
}
Part d:
ABDULLAH FAROOQ: 2015-EE-404
PP 6.8: Write a program that prints a table showing a subset of the Unicode characters and their
numeric values.
import java.util.Scanner;
public class PP6_8
{
public static void main(String[]args)
{
int i;
for(i=32;i<=126;i++)
ABDULLAH FAROOQ: 2015-EE-404
{
System.out.print(i + "----> " + (char)i+ "\t\t");
}
System.out.println();
}
}
PP 6.9: Write a program that reads three strings from the user, then determines and prints how many
times the letters ‘e’ appears in the first string, ‘t’ appears in the second string and ‘n’ appears in the
third string. Have a separate counter for each letter.
import java.util.Scanner;
public class PP6_9
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
String s1, s2, s3 ;
int i, j, k;
int sum=0;
int a, b, c;
System.out.println("Enter String-One");
s1 = scan.nextLine();
System.out.println("Enter String-2nd");
s2 = scan.nextLine();
System.out.println("Enter String-3rd");
s3 = scan.nextLine();
for(i=0;i<s1.length();i++)
{
a=s1.charAt(i);
if(a=='e')
sum+=1;
}
System.out.println("Number of \"E\" in String :" + sum);
sum=0;
for(j=0;j<s2.length();j++)
{
b=s2.charAt(j);
if(b=='t')
sum+=1;
}
System.out.println("Number of \"T\" in String :" + sum);
ABDULLAH FAROOQ: 2015-EE-404
sum=0;
for(k=0;k<s3.length();k++)
{
c=s3.charAt(k);
if(c=='n')
sum+=1;
}
System.out.println("Number of \"N\" in String :" + sum);
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 7.1: Modify the Account class from Chapter 4 so that it also permits an account to be opened with
just a name and an account number, assuming an initial balance of zero. Modify the main method of
the Transactions class to demonstrate this new capability.
Class:
import java.text.NumberFormat;
public class PP7_1i{
private final double RATE = 0.123;
private long acctNumber;
private double balance;
private String name;
public PP7_1i (String owner, long account){
name = owner;
acctNumber = account;
balance =0;
}
public double deposit (double amount){
balance = balance + amount;
return balance;
}
public double withdraw (double amount, double fee){
balance = balance - amount - fee;
return balance;
}
public double addInterest (){
balance += (balance * RATE);
return balance;
}
public double getBalance (){
return balance;
}
public String toString (){
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "\t" + name + "\t " + fmt.format(balance);
}}
Driver Class:
import java.util.*;
public class PP7_1ii
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Ur Name And Accout Number");
PP7_1i acct1 = new PP7_1i (scan.nextLine(),scan.nextLong());
double aaqibBalance = acct1.deposit (0);
System.out.println ("Balance after deposit: " + aaqibBalance);
System.out.println ("Balance after Interest: " + acct1.addInterest());
System.out.println ();
System.out.println (acct1);}}
ABDULLAH FAROOQ: 2015-EE-404
PP 7.2: Modify the Student class presented in this chapter as follows. Each student object should also
contain the scores for three tests.
Class:
public class PP7_2i{
private String firstName, lastName;
private int test1=0,test2=0,test3=0;
}}
Driver Class:
import java.util.Scanner;
public class PP7_2ii{
public static void main(String[] args){
PP7_2i S1;
S1=new PP7_2i("Abdullah","Farooq");
S1.setTestScore(1,10);
S1.setTestScore(2,9);
S1.setTestScore(3,10);
System.out.println(S1);
}}
PP 7.3: Write a class called Course that represents a course taken at a school. Represent each student
using the modified Student class from the previous programming project. Use an ArrayList in the
Course to store the students taking that course.
Class:
import java.util.Scanner;
import java.util.ArrayList;
public class PP7_3i
{
private String course;
ArrayList<String> students=new ArrayList<String>();
int n=0;
public PP7_3i(String course_)
{
course=course_;
}
public void addStudent(String student)
{
n++;
students.add(student);
}
public void roll()
{
int index;
index=students.size();
for(int p=0;p<index;p++)
{
System.out.println(students.get(p));
ABDULLAH FAROOQ: 2015-EE-404
}
}
public void averages()
{
int testScore=0;
Scanner scan=new Scanner(System.in);
for(int i=0;i<students.size();i++)
{
System.out.println("enter the test Score of "+students.get(i));
testScore +=scan.nextInt();
}
System.out.println("Average of all Student testScore is "+(double) testScore/(students.size()));
}
}
Driver Class:
public class PP7_3ii
{
public static void main(String[] args)
{
PP7_3i math;
math=new PP7_3i("Math");
math.addStudent("MUHAMMAD UMAIR");
math.addStudent("MUHAMMAD ALI");
math.addStudent("ALI ASLAM");
math.addStudent("MUHAMMAD ADNAN");
math.addStudent("MUHAMMAD ZAIN");
math.addStudent("MUHAMMAD UMER");
math.addStudent("MUHAMMAD YASIR");
math.addStudent("SALEEM SAFDER");
math.roll();
math.averages();
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 7.5: Write a Java interface called Priority that includes two methods: setPriority and getPriority.
The interface should define a way to establish numeric priority among a set of objects. Design and
implement a class called Task that represents a task (such as on a to-do list) that implements the
Priority interface. Create a driver class to exercise some Task objects.
Interface:
System.out.println(ta3);
System.out.println(ta5);
System.out.println(ta4);
ta1.setPriority(4);
ta2.setPriority(1);
System.out.println(ta1);
System.out.println(ta2);
}
}
ABDULLAH FAROOQ: 2015-EE-404
PP 8.1: Write a program that reads an arbitrary number of even integers that are in the range 2 to 100
inclusive and counts how many occurrences of each are entered. Indicate the end of the input by an
odd integer.
import java.util.ArrayList;
import java.util.Scanner;
public class PP8_1
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int num,index;
System.out.println("Enetr EVEN Number(2-100)");
num=scan.nextInt();
if(num%2==0 && num>=0 && num<=100)
{
while(num%2==0 && num>=0 && num<=100)
{
list.add(num);
System.out.println("Enter EVEN Number(2-100) or ODD for quit.");
num=scan.nextInt();
}
}
else
{
System.out.println("You Enter Odd integer...");
System.out.println("You Enter OUT-Of-RANGE integer...");
}
System.out.println(" " + list);
for(int j=0;j<list.size();j++)
{
int count=0;
for(int i=0;i<list.size();i++)
{
if(list.get(j)==list.get(i))
{
count+=1;
}
}
System.out.println("Your "+(j+1)+ " Number occurs " + count + " times...");
}}}
ABDULLAH FAROOQ: 2015-EE-404
PP 8.2: Modify the program from PP 8.1 so that it works for odd numbers and indicates end of input
by an even integer.
import java.util.ArrayList;
import java.util.Scanner;
public class PP8_2
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int num,index;
System.out.println("Enetr ODD Number(1-99)");
num=scan.nextInt();
if(num%2!=0 && num<=99 && num>0)
{
while(num%2!=0 && num<=99 && num>0)
{
list.add(num);
System.out.println("Enter ODD Number(1-99)");
num=scan.nextInt();
}
}
else
{
System.out.println("You Enter EVEN integer...");
System.out.println("You Enter OUT-Of-RANGE integer...");
}
System.out.println(" " + list);
for(int j=0;j<list.size();j++)
{
int count=0;
for(int i=0;i<list.size();i++)
{
if(list.get(j)==list.get(i))
{
count+=1;
ABDULLAH FAROOQ: 2015-EE-404
}
}
System.out.println("Your "+(j+1)+ " Number occurs " + count + " times...");
}}}
PP 8.3: Write a program that creates a histogram that allows you to visually inspect the score
distribution of a set of students.
import java.util.Scanner;
public class PP8_3
{
public static void main(String[]args)
{
Scanner scan=new Scanner(System.in);
int num,a;
int[] hash=new int[10];
System.out.println("Enter arbitrary number in range 0-100.Enter 101 to end input");
num=scan.nextInt();
while(num<=100)
{
for(a=0;a<100;a+=10)
{
if(num>=a&&num<=a+10)
hash[a/10]++;
}
System.out.println("Enter arbitrary number in range 0-100.Enter 101 to end input");
num=scan.nextInt();
}
System.out.println("Range\tStudents");
for(a=90;a>=0;a-=10)
{
int b=hash[a/10];
System.out.print(a+"-"+(a+10)+" \t ");
for(int c=0;c<b;c++)
System.out.print("#");
System.out.println();
}}}
ABDULLAH FAROOQ: 2015-EE-404
PP 8.5: Write a program that computes and prints the mean and standard deviation of a list of
integers x1 through xn.
import java.util.Scanner;
public class PP8_5
{
public static void main(String[]args)
{
int[] array=new int[5];
Scanner scan = new Scanner(System.in);
int n,sum=0;
double mean,sd=0,cc;
for(int i=0;i<5;i++)
{
System.out.print("Enter " + (i+1) +" numbers to get MEAN & SD");
n=scan.nextInt();
array[i]=n;
for(int j=0;j<5;j++)
{
sum+=array[j];
}
System.out.println(" SUM is : " + sum);
System.out.print("\t");
mean=(double)sum/5;
System.out.println(" MEAN is : " + mean);
System.out.print("\t"+"\t");
for( int k=0; k<5;k++)
{
ABDULLAH FAROOQ: 2015-EE-404
double x,y,z;
x=array[k]-mean;
y=x*x;
z=(0.5)*y;
sd+=z;
}
System.out.println(" SD is : " + sd);
}}
PP 8.6: The L&L Bank can handle up to 30 customers who have savings accounts. Design and
implement a program that manages the accounts. Keep track of key information and allow each
customer to make deposits and withdrawals.
import java.util.Scanner;
public class PP8_6
{
public static void main(String[]args)
{
char[] a = {'a','b','c','d','e','f','g','h','i','j','k',
'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D'};
int[] n= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29,30};
Scanner scan= new Scanner(System.in);
Scanner input= new Scanner(System.in);
String another="Y";
int num,amt1=0,amt2=0,blnc=0;
char na;
final double RATE=0.035;
System.out.println("Enter Your Account name (97-122) and (65-68) : ");
System.out.println("Your Account name Should be Numeric in above RANGEE.... ");
na=(char)input.nextInt();
System.out.println("Enter your account number : ");
num = input.nextInt();
for(int i=0;i<30;i++)
{
if(na==a[i] && num==n[i])
{
System.out.println(" WELCOME");
ABDULLAH FAROOQ: 2015-EE-404
PP 8.9: Modify the program you created in PP 8.8 to support the storing of additional employee
information: designation (string), department (string), experience (integer), and 10-digit phone
number.
import java.util.Scanner;
public class PP8_9
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
String[] list1 = new String[20];
String[] list2 = new String[20];
int[] list3 = new int[20];
String[] desig = new String[20];
String[] deptt = new String[20];
int[] exp = new int[20];
int[] phone = new int[20];
String fname,lname,desi,dept;
int id,expr,pn;
int i,j;
for(i=0;i<1;i++)
{
System.out.println("Enter FIRST name : ");
fname=scan.nextLine();
list1[i]=fname;
System.out.println("Enter LAST name : ");
lname=scan.nextLine();
list2[i]=lname;
System.out.println("Enter Your ID : ");
id=input.nextInt();
list3[i]=id;
System.out.println("Enter Your Designation : ");
desi=scan.nextLine();
desig[i]=desi;
System.out.println("Enter Your Department : ");
dept=scan.nextLine();
deptt[i]=dept;
System.out.println("Enter Your Experience from (1--10) : ");
expr=input.nextInt();
exp[i]=expr;
System.out.println("Enter Your Phone-Number with area-code : ");
pn=input.nextInt();
phone[i]=pn;
}
ABDULLAH FAROOQ: 2015-EE-404
for(j=0;j<1;j++)
{
System.out.println("First name : " + list1[j] + "\t" + "Last name : " + list2[j] + "\t" +
"Your ID is : "+ list3[j] + "\t" + "Designation : " + desig[j]+ "\t" +
" Depatment : "+deptt[j]+"\t"+"Experience : "+exp[j]+"\t" + "Phone-Number : " +phone[j]);
}}}