Você está na página 1de 73

Advanced Programming in java(16103037)

Dr. B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY


JALANDHAR – 144011, PUNJAB (INDIA)

Jul-Dec, 2018

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Advanced Programming in Java

Submitted to: Submitted by:


Dr. Paramvir Singh Kajal (16103037)
Associate Professor
1
Page

2016-2020 Page 1
Advanced Programming in java(16103037)

Program Index
S.No. Lab Name of the Program Page
1 1 Introduction to JAVA 3-4
2 2 Introduction to ECLIPSE 5
3 3 Introduction to VERSION CONTROL 6
SYSTEM

4 4 Introduction to GIT 7-8


5 5 Assignment 1- Student Grading Using File 9-12
I/O and Arrays
6 6 Assignment 2- Searching and Sorting 13-15
7 7 Assignment 3- Dynamic memory, 16-22
Searching and Strings
8 8 Assignment 4- Stack Sort 23-25
9 9 26-29
Assignment 5-List Implementation
10 10 Assignment 6- Stock Holding 30-42
11 11 Assignment 7- Test, ATM, Lottery 43-53
12 12 Assignment 8- Recursion 54-58
13 13 Assignment 9- Link Based Bag 59-65
Implementation
14 14 Assignment 10- Counting Games, Primes 66-70

15 15 Assignment 11- Producer Consumer 71-73


Problem
2
Page

2016-2020 Page 2
Advanced Programming in java(16103037)

Introduction
1.Java

Java is a programming language created by James Gosling from Sun Microsystems


(Sun) in 1991. The target of Java is to write a program once and then run this
program on multiple operating systems. The first publicly available version of Java
(Java 1.0) was released in 1995. Sun Microsystems was acquired by the Oracle
Corporation in 2010. Oracle has now the steermanship for Java. In 2006 Sun
started to make Java available under the GNU General Public License (GPL).
Oracle continues this project called OpenJDK.

Over time new enhanced versions of Java have been released. The current version
of Java is Java 1.8 which is also known as Java 8.

Java is defined by a specification and consists of a programming language, a


compiler, core libraries and a runtime (Java virtual machine) The Java runtime
allows software developers to write program code in other languages than the Java
programming language which still runs on the Java virtual machine. The Java
platform is usually associated with the Java virtual machine and the Java core
libraries.

The Java language was designed with the following properties:

Platform independent: Java programs use the Java virtual machine as abstraction
and do not access the operating system directly. This makes Java programs highly
portable. A Java program (which is standard-compliant and follows certain rules)
can run unmodified on all supported platforms, e.g., Windows or Linux.

Object-orientated programming language: Except the primitive data types, all


elements in Java are objects.

Strongly-typed programming language: Java is strongly-typed, e.g., the types of


the used variables must be pre-defined and conversion to other objects is relatively
strict, e.g., must be done in most cases by the programmer.

Interpreted and compiled language: Java source code is transferred into the
3

bytecode format which does not depend on the target platform. These bytecode
Page

instructions will be interpreted by the Java Virtual machine (JVM). The JVM
2016-2020 Page 3
Advanced Programming in java(16103037)

contains a so called Hotspot-Compiler which translates performance critical


bytecode instructions into native code instructions.

Automatic memory management: Java manages the memory allocation and de-
allocation for creating new objects. The program does not have direct access to the
memory. The so-called garbage collector automatically deletes objects to which no
active pointer exists.
4
Page

2016-2020 Page 4
Advanced Programming in java(16103037)

2.Eclipse Introduction

Eclipse is a cross-platform IDE developed by Eclipse Foundation. It came in the


year 2001 and is currently the most widely used Java IDE. It is used for developing
applications in Java, Ruby, C, C++, etc. Under Eclipse Introduction, we will
discuss about the Eclipse, version history and its features.

Eclipse is free to download and released under the Eclipse Public License (EPL).

Features

Open Source: Eclipse is an open source IDE, which is freely available. Go to its
official website, download and install for free.

Rich Client Platform: Eclipse provides the Rich Client Platform (RCP) for
developing general purpose applications.

Eclipse Workbench: It includes views, editors, perspectives, etc.

Extensions: Eclipse has a lot of extensions, which helps in integration and support
for Python, Android, jQuery, etc.

Plugins: Eclipse supports a lot of plugins. Also, you can also write your own plug-
ins using the Plug-in Development Environment (PDE).

Eclipse Marketplace: A universe of extensions and plugins is provided by Eclipse


at the Marketplace.

Tools: Eclipse provides tools to help you in analyzing your code, managing,
refactoring it, etc. It also has plugins for defect detection, automatically correcting
code quality defects, etc.

Accessibility: Eclipse takes care of the users with restricted mobility, partial
impairment and provides the IDE access using keyboard, With that, you can use
screen-reader software to hear what is written.
5
Page

2016-2020 Page 5
Advanced Programming in java(16103037)

3.Version Control System

Version control systems are a category of software tools that help a software team
manage changes to source code over time. Version control software keeps track of
every modification to the code in a special kind of database. If a mistake is made,
developers can turn back the clock and compare earlier versions of the code to help
fix the mistake while minimizing disruption to all team members.

Version Control Systems (VCS) have seen great improvements over the past few
decades and some are better than others. VCS are sometimes known as SCM
(Source Code Management) tools or RCS (Revision Control System). One of the
most popular VCS tools in use today is called Git. Git is a Distributed VCS.
6
Page

2016-2020 Page 6
Advanced Programming in java(16103037)

4.Git

The most widely used modern version control system in the world today is Git. Git
is a mature, actively maintained open source project originally developed in 2005
by Linus Torvalds, the famous creator of the Linux operating system kernel. A
staggering number of software projects rely on Git for version control, including
commercial projects as well as open source. Developers who have worked with Git
are well represented in the pool of available software development talent and it
works well on a wide range of operating systems and IDEs (Integrated
Development Environments).

Having a distributed architecture, Git is an example of a DVCS (hence Distributed


Version Control System). Rather than have only one single place for the full
version history of the software as is common in once-popular version control
systems like CVS or Subversion (also known as SVN), in Git, every developer's
working copy of the code is also a repository that can contain the full history of all
changes.

In addition to being distributed, Git has been designed with performance, security
and flexibility in mind.

Performance

The raw performance characteristics of Git are very strong when compared to
many alternatives. Committing new changes, branching, merging and comparing
past versions are all optimized for performance. The algorithms implemented
inside Git take advantage of deep knowledge about common attributes of real
source code file trees, how they are usually modified over time and what the access
patterns are.

Security

Git has been designed with the integrity of managed source code as a top priority.
The content of the files as well as the true relationships between files and
directories, versions, tags and commits, all of these objects in the Git repository are
secured with a cryptographically secure hashing algorithm called SHA1. This
7

protects the code and the change history against both accidental and malicious
Page

change and ensures that the history is fully traceable.


2016-2020 Page 7
Advanced Programming in java(16103037)

Flexibility

One of Git's key design objectives is flexibility. Git is flexible in several respects:
in support for various kinds of nonlinear development workflows, in its efficiency
in both small and large projects and in its compatibility with many existing systems
and protocols.

Version control with Git

Git is the best choice for most software teams today. While every team is different
and should do their own analysis, here are the main reasons why version control
with Git is preferred over alternatives:

Git is good

Git has the functionality, performance, security and flexibility that most teams and
individual developers need. These attributes of Git are detailed above. In side-by-
side comparisons with most other alternatives, many teams find that Git is very
favorable.

Git is a quality open source project


8
Page

2016-2020 Page 8
Advanced Programming in java(16103037)

Assignment 1

Problem: Student Grading Using File I/O and Arrays

The purpose of this assignment is to review the use of one-dimensional arrays, reading and
writing text files, writing functions, and program planning and development.
This program consists of two parts:
1) Part 1: read and process a student data file, and writing the results to a student report file
2) Part 2: add code to part 1 to calculate some statistics and write them to the end of student
report file.
For this assignment, you will be reading one input file and writing out to an output file.
Code:
import java.util.StringTokenizer;
import java.io.*;
public class CSX_358_HW1_16103037 {
public static void main(String args[]){
String fileName = "F:\\java_assignments\\HW1-data.txt";
String pre = null;
String thisLine=null;
try {
int count = 0,max=0,a=0,b=0,c=0,d=0,f=0;
double totper=0, pct=0;
char grade;
FileReader fileReader = new FileReader(fileName);
BufferedReader reader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter("F:\\java_assignments\\HW1-output-
16103037.txt");
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("Stdnt Id Ex ------- Assignments --------- Tot Mi Fin CL Pts Pct
Gr");
writer.newLine();
writer.write("-------- -- ----------------------------- --- -- --- -- --- --- --");
writer.newLine();
int data[]=new int [15];
while((thisLine=reader.readLine())!=null){
count++; //to count to total no of students
StringTokenizer token = new StringTokenizer(thisLine); //allows string to break into tokens in
a line
for(int j=0;j<15;j++){
String s = token.nextToken();
data[j]=Integer.parseInt(s); //convert string to int }
int total =0;
for(int j=2;j<12;j++)
9

total=total+data[j]; //Sum of all assignment marks


Page

int Pts=0; //Points in report card

2016-2020 Page 9
Advanced Programming in java(16103037)

for(int j=1;j<15;j++)
Pts=Pts+data[j];
if(Pts>max) //max returns max points scored
max=Pts;
pct=((Pts*100)/420); //pct is percentage
totper=totper+pct; //total percentage of class for finding average percentage
if(Math.round(pct)>=90) //Math.round for rounding off to close numer
{grade='A';
a++; }
else if(Math.round(pct)<90 && Math.round(pct)>=78) {
grade='B'; b++; }
else if(Math.round(pct)<78 && Math.round(pct)>=62) {
grade='C'; c++; }
else if(Math.round(pct)<62 && Math.round(pct)>=46) {
grade='D'; d++; }

else {grade='F'; f++; }


if(data[0]/10000000<1) { //to check if roll no is starting with 0
pre="0"+Integer.toString(data[0]);//then we add 0 and add it to roll no converting it to string
writer.write(pre+" ");
else
writer.write(data[0]+" ");
writer.write(data[1]+" ");
for(int i=2;i<12;i++) {
if(data[i]/10<1)
writer.write(" "+data[i]+" ");
else
writer.write(data[i]+" ");}
writer.write(" ");
writer.write(total+" ");
writer.write(data[12]+" ");
writer.write(" "+data[13]+" ");
if(data[14]/10<1)
writer.write(" "+data[14]+" ");
else
writer.write(data[14]+" ");
writer.write(Math.round(Pts)+" "); writer.write(" "+Math.round(pct)+" ");
writer.write(" "+grade); writer.newLine(); }
writer.newLine();
writer.write("-----Summary of Report-----");
writer.newLine();
writer.write("Average total point percent of all students: "+totper/count+" %");
writer.newLine(); writer.write("Number of A's = "+a); writer.newLine();
10

writer.write("Number of B's = "+b); writer.newLine();


writer.write("Number of C's = "+c); writer.newLine(); writer.write("Number of D's = "+d);
Page

writer.newLine(); writer.write("Number of F's = "+f);

2016-2020 Page 10
Advanced Programming in java(16103037)

writer.newLine(); writer.write("Maximum points = "+max);


reader.close(); writer.close(); }
catch(IOException ex) {
ex.printStackTrace();
}}}
Output:
11
Page

2016-2020 Page 11
12
Page
Advanced Programming in java(16103037)

2016-2020 Page 12
Advanced Programming in java(16103037)

Assignment 2

Problem: Searching and Sorting

The purpose of this assignment is to give you practice working with arrays, passing them to
functions, sorting, searching and reading and writing text files.
In this program you will read two files and store their contents in arrays. You will sort both
arrays, and then search an array for each element of the second array.
Program Steps
 Open two input files and one output file.
 Input files
 HW2-dictionary.txt - this file contains 16000 words
 HW2-keywords.txt - this file contains 84 words
 Read in these two files and store their contents in 2 arrays of strings.
 Sort both arrays using either a selection sort, bubble sort or insertion sort. Use the same
sort routine for sorting both arrays.
 Search the dictionary array for each keyword. If the keyword is not present in the
dictionary array, write a message to the output file that the keyword is not found in the
dictionary (see sample output below). Count the number of keywords not found. You
will print this number at the end of the program.
Code:
import java.io.*; import java.util.Vector;
public class assign2 {
public static void main(String args[]){
String dict = "F:\\java_assignments\\HW2-dictionary.txt"; //two input files
String keywds="F:\\java_assignments\\HW2-keywords.txt"; int kcount=0;
Try{ BufferedReader dbr=new BufferedReader(new FileReader(dict)); BufferedReader kbr=new
BufferedReader(new FileReader(keywds));
FileWriter fileWriter = new FileWriter("F:\\java_assignments\\HW2-output-16103037.txt"):
//the output file
BufferedWriter writer = new BufferedWriter(fileWriter);
String dic[]=new String [16000];
String key[]=new String [84];
for(int i=0;i<16000;i++){ dic[i]=dbr.readLine();
13

} for(int i=0;i<84;i++) { key[i]=kbr.readLine(); }


Page

2016-2020 Page 13
Advanced Programming in java(16103037)

String tempStr,temp;
for (int t = 0; t < 16000 - 1; t++) {
for (int i= 0; i < 16000 - t-1; i++) {
if(dic[i+1].compareTo(dic[i])<0) {
tempStr = dic[i];
dic[i] = dic[i + 1];
dic[i + 1] = tempStr;
}}}
for (int t = 0; t < 84 - 1; t++) {
for (int i= 0; i < 84 - t-1; i++) {
if(key[i+1].compareTo(key[i])<0) {
temp = key[i];
key[i] = key[i + 1];
key[i + 1] = temp; }}}
int flag=0;
try {
for(int t=0;t<84;t++) { for(int i=0;i<16000;i++)
{ if(key[t].equals(dic[i])) { flag=1;
}}
if(flag==0) { writer.write("Keyword not found: " + key[t] );
writer.newLine(); kcount++; }
flag=0; }
writer.newLine(); writer.write("No. of keywords not found: "+ kcount);
writer.close(); kbr.close(); dbr.close(); }
catch (Exception e){ System.out.println("Exception occurred"); }}
catch(FileNotFoundException fne){
14

fne.printStackTrace();
Page

2016-2020 Page 14
Advanced Programming in java(16103037)

catch(IOException io){ io.printStackTrace(); }}}


Output:
15
Page

2016-2020 Page 15
Advanced Programming in java(16103037)

Assignment 3

Problem: Dynamic memory, searching and strings.

The purpose of this assignment is to give you practice using dynamic memory allocation, string
functions, sorting, and searching. You will write a program to check keyword occurrence and
test it.

Program Steps
1. Read an unsorted keywords file once to determine how many words are in the file.
2. Allocate memory dynamically to store the unsorted keywords in an array of strings.
3. Reread the keywords file a second time and store the words in the dynamically allocated
array of strings.
4. Sort the array of key words. (Hint: be sure to check your sorted array of key words -
there should be 84)
5. Search a C++ program input file for occurrences of the keywords:
○ Read one line at a time from the code file.
○ Parse each line into separate words. Ignore any words that are inside a
comment.
○ Search the keyword array to determine if each word is a keyword.
○ For keywords, print the line number, the keyword, and the position of the
keyword in the line.
○ Keep a count of the number of keywords found
Code:
import java.util.*;
import java.io.*;
public class keywordSorting {
public static void main(String args[])throws Exception {
File keywordFile =new File("F:\\java_assignments\\HW3-unsorted-
keywords.txt"); //input unsorted file
FileWriter fileWriter = new FileWriter("F:\\java_assignments\\HW3-
OUTPUT-16103037.txt"); //output file
File input_code=new File("F:\\java_assignments\\HW3-input-code.cpp");
//input code files
BufferedWriter writer = new BufferedWriter(fileWriter); // buffer
writer
Scanner s= new Scanner(keywordFile); //keyword file scanner
Scanner file_code= new Scanner(input_code); //input code file
16

scanner
Page

int i=0; //to read file line by line

2016-2020 Page 16
Advanced Programming in java(16103037)

while(s.hasNextLine()) {
//to count the no. of keywords
String d=s.nextLine();
if(d.length()>0) i++; }
int counter=0;
String a[]=new String[i]; int j=-1; s.close();
s= new Scanner(keywordFile);
while(s.hasNextLine()) {
// to count the no. of the keywords.
String d=s.nextLine();
if(d.length()>0) { j++; a[j]=d; } }
j++; int k,l;
for(k=1;k<j;k++) {
// sorting the strings
for(l=0;l<j-k;l++) {
if(a[l+1].compareTo(a[l])>0) {
String g=a[l+1]; a[l+1]=a[l]; a[l]=g;
} }}
String g; i=0;
while(file_code.hasNextLine()) //checking of input code file
{i++; int flag=0;
g=file_code.nextLine();
String x="line "+i+": ";
for(k=0;k<g.length();k++)
der:{int r=k; char w=g.charAt(k);
if(w=='/'&& g.charAt(k+1)=='/') { break;
if(w>='a'&&w<='z'||w>='0'&& w<='9'||w=='_') //keyword checking
{ String q="";
while(w>='a'&&w<='z'||w>='0'&&w<='9'||w=='_')
{ q=q+w; k++;
if(k<g.length())
w=g.charAt(k);
else
w='&'; }k=k-1;
int y,u,h; y=0; u=j-1;
while(y<=u) { h=(y+u)/2;
if(q.compareTo(a[h])==0) { flag=1;
counter++; x=x+q+"("+r+") ";
break; }
else if(q.compareTo(a[h])>0)
u=h-1;
else
17

y=h+1; }}
else { if(w=='/') { k++;
Page

w=g.charAt(k);

2016-2020 Page 17
Advanced Programming in java(16103037)

if(w=='/'){
break der; }
else
k=k-1; }}}
if(flag==1) {
x=x+"\n";
writer.write(x); // writing found keywords into the output file
writer.newLine(); System.out.print(x); } }
String f="Number of keywords found : "+counter+"\n";
System.out.print(f); writer.write(f);
s.close(); file_code.close();
writer.close();}}

Output:
18
Page

2016-2020 Page 18
19
Page
Advanced Programming in java(16103037)

2016-2020 Page 19
20
Page
Advanced Programming in java(16103037)

2016-2020 Page 20
21
Page
Advanced Programming in java(16103037)

2016-2020 Page 21
22
Page
Advanced Programming in java(16103037)

2016-2020 Page 22
Advanced Programming in java(16103037)

Assignment 4
Problem: In this lab you will complete an application that uses the Abstract Data Type (ADT) stack.
Stack Sort
Code:
/**
* Use two stacks to sort the data in an array
*
* @param data An array of integer values to be sorted.
* @return An array of sorted integers.
*/
private static int[] doStackSort(int data[]) {
int result[] = new int[data.length];
// ADD CODE HERE TO SORT THE ARRAY USING TWO STACKS
VectorStack<Integer> a;
a= new VectorStack<Integer>(data.length);
VectorStack<Integer> b;
b= new VectorStack<Integer>(data.length);
int i;
for(i=0;i<data.length;i++)
{ if(!a.isEmpty()&&!b.isEmpty()) {
if(data[i]>=a.peek()&&data[i]<=b.peek()) {
a.push(data[i]); }
else if(data[i]>b.peek()) {
while(!b.isEmpty()&&data[i]>b.peek()) {
a.push(b.pop());
}
b.push(data[i]);
}
else if(data[i]<a.peek())
{
while(!a.isEmpty()&&data[i]<a.peek())
{
b.push(a.pop());
}
a.push(data[i]); }
}
else if(b.isEmpty())
{ while(!a.isEmpty()&&data[i]<a.peek()) {
b.push(a.pop()); }
23

a.push(data[i]);
Page

}
else if(a.isEmpty())
2016-2020 Page 23
Advanced Programming in java(16103037)

{ while(!b.isEmpty()&&data[i]>b.peek()) {
a.push(b.pop());
}
b.push(data[i]);
}
else
{
a.push(data[i]);
}
}
while(!a.isEmpty())
b.push(a.pop());
i=-1;
while(!b.isEmpty())
{
i++;
result[i]=b.pop();
}

return result;

/**
* Load an array with data values
*
* @param size The number of data values to generate and place in
the array.
* @param min The minimum value to generate.
* @param max The maximum value to generate.
* @return An array of randomly generated integers.
*/
private static int[] createArray(int size, int min, int max) {

Random generator = new Random();

// If we get a negative size, just make the size 1


if (size < 0) {
size = 1;
}
// We need max > min for the random number generator to be happy
if (max <= min) {
max = min + 1;
24

}
Page

2016-2020 Page 24
Advanced Programming in java(16103037)

int[] data = new int[size];


for (int i = 0; i < size; i++) {
data[i] = min + generator.nextInt(max - min);
}

return data;
}

Output:
25
Page

2016-2020 Page 25
Advanced Programming in java(16103037)

Assignment 5

Problem: List Implementation


In this lab you will explore two implementations of the ADT list. The first implementation will
use an array and the second will use a linked structure. In both cases you will create new
methods that work directly with the implementations. You will implement a reverse method that
will reverse the order of the items in the list. You will also implement a cycle method that will
move the first item in the list to the last position.
Java Files
 AList.java
 ArrayListExtensionsTest.java
 LList.java
 LinkedListExtensionsTest.java
 ListInterface.java
Code:
Alist:

/** Reverse the order of items in a list.


*/
public void reverse()
{
//METHODS TO BE COMPLETED
//checking that list is not empty
if(!this.isEmpty())
{
int length=this.getLength();
int i=1,j=length;
T temp;
while(i<j)
{temp=this.getEntry(i);
list[i]=this.getEntry(j);
list[j]=temp;
i++ ; j--;
} } }
/** Cycle the first item to the end of the list.
*/
public void cycle()
{
T first=this.getEntry(1); //first entry saving
26

int length=this.getLength(); //getting length of list


int i=1,j=i+1;
Page

T temp;

2016-2020 Page 26
Advanced Programming in java(16103037)

while(i<length) {
temp=this.getEntry(i);
list[i]=this.getEntry(j); //swapping
list[j]=temp;
j++;i++; }
list[j]=first; }}

LLIst:
/** Reverse the order of items in a list.
*/
public void reverse() { //Checking list is not empty
if(!this.isEmpty())
{
int length=this.getLength(); //Getting length of the list
int i=1,j=length; //initializing first and last element
T temp; //declaring temp
//Swapping the ith and jth elements from beginning and end
while(i<j){
temp=this.getEntry(i); //initialize temp with ith entry of list
this.replace(i,this.getEntry(j));
//replace ith entry of list with jth entry
this.replace(j, temp); //replace jth entry with temp
i++;j--; //increment i and decrement j
}} }
/** Cycle the first item to the end of the list.
*/
public void cycle() {
//checking that list is not empty
if(!this.isEmpty())
{
T first=this.getEntry(1); //initialize y as
first element of list
this.remove(1); //now remove first from list and
this.add(first); //add it to the end of this list
} }}

Output:
27
Page

2016-2020 Page 27
28
Page
Advanced Programming in java(16103037)

2016-2020 Page 28
29
Page
Advanced Programming in java(16103037)

2016-2020 Page 29
Advanced Programming in java(16103037)

Assignment 6
Problem: 1. Create a class called StockHolding to represent a stock that you have purchased.
For instance variables, it will have two floats named purchaseSharePrice and currentSharePrice,
one int named numberOfShares and one string named companyName. Create accessor methods
for the instance variables. Create two other instance methods:
- (float)costInDollars; // purchaseSharePrice * numberOfShares
- (float)valueInDollars; // currentSharePrice * numberOfShares
2. Create a subclass of StockHolding called ForeignStockHolding. Give ForeignStockHolding an
additional instance variable: conversionRate, which will be a float. (The conversion rate is what
you need to multiply the local price by to get a price in Canadian dollars. Assume the
purchasePrice and currentPrice are in the local currency.) Override costInDollars and
valueInDollars to do the right thing.
Add at least two instances of ForeignStockHolding to the existing array from part one.
Display all the stocks sorted by company name in reverse alphabetical order.

Code:
1. Foreign Stock Holding:
package stock;
//a subclass of StockHolding called ForeignStockHolding
public class ForeignStockHolding extends StockHolding
{
float conversionRate; /* an additional instance variable:
conversionRate of float type,
* (The conversion rate is what you need to multiply
* the local price by to get a price in Canadian dollars.
* Assume the purchasePrice and currentPrice are in the local
currency.)*/
ForeignStockHolding(float purchasePrice, float currentPrice, int
noOfShare, String cname, float conRate)
{
super(purchasePrice, currentPrice, noOfShare, cname);
/*"super" (a special variable), for use in the definitions
of instance methods.
* The variable super is for use in a subclass. Like this,
super refers to the object that contains the method.
* The reason super exists is so you can get access to
things in the superclass that are hidden by things in the subclass.
30

*/
conversionRate = conRate;
Page

2016-2020 Page 30
Advanced Programming in java(16103037)

/* Override costInDollars and valueInDollars to do the right


thing. */
float costInDollars()
{
return conversionRate*purchaseSharePrice*numberOfShares;
}

float valueInDollars()
{
return conversionRate*currentSharePrice*numberOfShares;
}}

2. Stock.java
package stock;
import java.util.*;
public class Stock{
//function to display StockHolding in ascending order
static void displayAscending(StockHolding array[]) {
//selection sort
for(int i=0; i<array.length; i++){
//temp is a variable used to swap 2 object in array
StockHolding temp;
for(int j=i+1; j<array.length; j++)
{
//if value at index j is lexicographically smaller than that at i swap
them
if((array[j].companyName.compareTo(array[i].companyName)) < 0)
{
temp = array[j];
array[j]=array[i]; //swapping
array[i]=temp; } } }
//print all the details on screen
System.out.println("Display of stock in ascending order by name : ");
for(int i=0; i<array.length; i++)
{
System.out.println("Company Name :
"+array[i].companyName);System.out.println("Purchase Share Price :
"+array[i].purchaseSharePrice);
System.out.println("Current Share Price :
"+array[i].currentSharePrice);
System.out.println("Number of Shares : "+array[i].numberOfShares);
31

System.out.println();
}}
Page

2016-2020 Page 31
Advanced Programming in java(16103037)

//function to display ForeignStockHolding in descending order


static void displayDescending(ForeignStockHolding array[]) {
//selection sort
for(int i=0; i<array.length; i++) {
ForeignStockHolding temp;
for(int j=i+1; j<array.length; j++) { //if value at index j is
lexicographically greater than that at i swap them
if((array[j].companyName.compareTo(array[i].companyName)) > 0)
{
temp = array[j]; array[j]=array[i]; //swapping
array[i]=temp;
}}}
//printing the stock in descending order
System.out.println("Display of stock in descending order by name : ");
for(int i=0; i<array.length; i++){
System.out.println("Company Name : "+array[i].companyName);
System.out.println("Purchase Share Price :
"+array[i].purchaseSharePrice);
System.out.println("Current Share Price :
"+array[i].currentSharePrice);
System.out.println("Number of Shares : "+array[i].numberOfShares);
System.out.println("Conversion Rate : "+array[i].conversionRate);
System.out.println();
}}
//function to display ForeignStockHolding in ascending order
static void displayAscending(ForeignStockHolding array[]) {
//selection sort
for(int i=0; i<array.length; i++) {
ForeignStockHolding temp;
for(int j=i+1; j<array.length; j++) {
//if value at index j is lexicographically less than that at i swap
them
if((array[j].companyName.compareTo(array[i].companyName)) < 0)
{
temp = array[j]; array[j]=array[i]; array[i]=temp;
}
}}
//printing the stock in ascending order
System.out.println("Display of stock in ascending order by name : ");
for(int i=0; i<array.length; i++)
{
System.out.println("Company Name : "+array[i].companyName);
System.out.println("Purchase Share Price :
32

"+array[i].purchaseSharePrice);
Page

2016-2020 Page 32
Advanced Programming in java(16103037)

System.out.println("Current Share Price :


"+array[i].currentSharePrice);
System.out.println("Number of Shares : "+array[i].numberOfShares);
System.out.println("Conversion Rate : "+array[i].conversionRate);
System.out.println(); }}
//function to display minimum value stock
static void displayMinValue (ForeignStockHolding array[])
{
//temp object of ForeignStockHolding to store minimum value stock
ForeignStockHolding temp = array[0];
//traversing the array to find the min value stock
for(int i=1; i<array.length; i++) {
if(temp.valueInDollars() > array[i].valueInDollars()) /*compare value
at temp and at ith position,if
*value a temp is bigger then replace it with value at ith*/
{
temp = array[i];
}}
//printing the minimum value stock
System.out.println("Minimum Value Stock :");
System.out.println("Company Name : "+temp.companyName);
System.out.println("Purchase Share Price : "+temp.purchaseSharePrice);
System.out.println("Current Share Price : "+temp.currentSharePrice);
System.out.println("Number of Shares : "+temp.numberOfShares);
System.out.println("Conversion Rate : "+temp.conversionRate);
System.out.println();
}
//function to display maximum value from stock
static void displayMaxValue (ForeignStockHolding array[])
{
//temp object of ForeignStockHolding to store max value stock
ForeignStockHolding temp = array[0];
//traversing the array to find the max value stock
for(int i=1; i<array.length; i++) {
if(temp.valueInDollars() < array[i].valueInDollars())
{
temp = array[i];
}}
//printing the maximum value stock
System.out.println("Maximum Value Stock :");
System.out.println("Company Name : "+temp.companyName);
System.out.println("Purchase Share Price : "+temp.purchaseSharePrice);
System.out.println("Current Share Price : "+temp.currentSharePrice);
33

System.out.println("Number of Shares : "+temp.numberOfShares);


Page

System.out.println("Conversion Rate : "+temp.conversionRate);

2016-2020 Page 33
Advanced Programming in java(16103037)

System.out.println();
}
//function to display maximum profitable stock from
ForeignStockHolding stocks
static void displayMaxProfitableStock(ForeignStockHolding array[])
{
//temp object of ForeignStockHolding to store max
profitable stock
ForeignStockHolding temp = array[0];

//traversing the array to find the max profitable stock


for(int i=1; i<array.length; i++)
{ //profit= (total revenue)-(total expenses)
if((temp.valueInDollars()-temp.costInDollars()) <
(array[i].valueInDollars()-array[i].costInDollars()))
//comparing,higher value will taken further
{
temp = array[i];
} }
//printing the maximum profitable stock information
System.out.println("Maximum Profitable Stock :");
System.out.println("Company Name : "+temp.companyName);
System.out.println("Purchase Share Price : "+temp.purchaseSharePrice);
System.out.println("Current Share Price : "+temp.currentSharePrice);
System.out.println("Number of Shares : "+temp.numberOfShares);
System.out.println("Conversion Rate : "+temp.conversionRate);
System.out.println();
}
//method to display information of the stock with minimum
profit value
static void displayMinProfitableStock(ForeignStockHolding array[])
{
//temp object of ForeignStockHolding to store minimum
profitable stock
ForeignStockHolding temp = array[0];

//traversing the array to find the minimum profitable


stock
for(int i=1; i<array.length; i++)
{ //profit=(total value that is in hand)-(total cost)

if((temp.valueInDollars()-temp.costInDollars()) >
(array[i].valueInDollars()-array[i].costInDollars()))
34
Page

/*comparing,lower value will

2016-2020 Page 34
Advanced Programming in java(16103037)

*taken further as minimum value of profit is


required */
{
temp = array[i];
}
}

//printing the minimum profitable stock


System.out.println("Minimum Profitable Stock :");
System.out.println("Company Name :
"+temp.companyName);
System.out.println("Purchase Share Price :
"+temp.purchaseSharePrice);
System.out.println("Current Share Price :
"+temp.currentSharePrice);
System.out.println("Number of Shares :
"+temp.numberOfShares);
System.out.println("Conversion Rate :
"+temp.conversionRate);
System.out.println();
}
//method to display sorted values of stocks
static void displayInSortedValueOrder (ForeignStockHolding
array[])
{
//selection sort
for(int i=0; i<array.length; i++)
{
ForeignStockHolding temp;
for(int j=i+1; j<array.length; j++)
{
//if value at index j is lexicographically
less than that at i swap them
if(array[j].valueInDollars() <
array[i].valueInDollars())
{
temp = array[j];
array[j]=array[i];
array[i]=temp;
}
}
}
35

//print in the stock in ascending order


Page

2016-2020 Page 35
Advanced Programming in java(16103037)

System.out.println("Display of stock in ascending


order by value : ");
for(int i=0; i<array.length; i++)
{
System.out.println("Company Name :
"+array[i].companyName);
System.out.println("Purchase Share Price :
"+array[i].purchaseSharePrice);
System.out.println("Current Share Price :
"+array[i].currentSharePrice);
System.out.println("Number of Shares :
"+array[i].numberOfShares);
System.out.println("Conversion Rate :
"+array[i].conversionRate);
System.out.println();
}
}
//defining main method
public static void main (String[] args)
{
//array of StockHolding with 3 values
StockHolding stockHoldingArray[] = new
StockHolding[3]; //declaring new StockHolding object
//giving static values all instant variables of
StockHolding class
stockHoldingArray[0] = new StockHolding((float)2.30,
(float)4.50, (int)40, "XYZ limited");
stockHoldingArray[1] = new StockHolding((float)12.19,
(float)10.56, (int)90, "ABC Pvt Limited");
stockHoldingArray[2] = new StockHolding((float)45.10,
(float)49.51, (int)210, "United States Limited");

//function to display in alphabetical order data of


StockHolding class
displayAscending(stockHoldingArray);

//array of ForeignStockHolding
ForeignStockHolding foreignStockHoldingArray[] = new
ForeignStockHolding[3];
//giving static values to instant variables of ForeignStockHolding
subclass
foreignStockHoldingArray[0] = new ForeignStockHolding((float)2.30,
(float)4.50, (int)40, "XYZ limited", (float)0.94);
36

foreignStockHoldingArray[1] = new ForeignStockHolding((float)12.19,


Page

(float)10.56, (int)90, "ABC Pvt Limited", (float)1.10);

2016-2020 Page 36
Advanced Programming in java(16103037)

foreignStockHoldingArray[2] = new ForeignStockHolding((float)45.10,


(float)49.51, (int)210, "United States Limited", (float)1.25);
//function to display in reverse alphabetical order
displayDescending(foreignStockHoldingArray);
//modifying the application according to the user
//taking no of stock from user
Scanner input = new Scanner(System.in);
System.out.print("Enter no of stocks(not more than 8) : ");
//no of stock user want to access
int noOfStocks = input.nextInt();
//declaring array of ForeignStockHolding as per user requirement
ForeignStockHolding userStockHoldingArray[] = new
ForeignStockHolding[noOfStocks];
for(int i=0; i<noOfStocks; i++){
//to take the type of stock user want to enter
int typeOfStock;
System.out.print("Press 1 for StockHolding \n 2 for
ForeignStockHolding \n");
//taking the type of stock
typeOfStock = input.nextInt();
//declaring the variable to take input for purchaseSharePrice,
currentSharePrice, conversionRate
float purchasePrice,currentPrice, conRate;
//declaring the variable to take input for numberOfShares
int noOfShare;
//declaring the variable to take input for companyName
String cname;
//taking input from user for each field specified in stock
System.out.print("Enter the purchaseSharePrice for stock : ");
purchasePrice = input.nextFloat();
System.out.print("Enter the currentSharePrice for stock : ");
currentPrice = input.nextFloat();
System.out.print("Enter the noOfShares for stock : ");
noOfShare = input.nextInt();
System.out.print("Enter the companyName for stock : ");
cname = input.next();

//if the stock is of type StockHolding then conversion rate is 1 else


take input from user
if(typeOfStock == 1)
{ conRate = 1;
}
else {
37

System.out.print("Enter the conversion Rate for foreign stock");


Page

conRate = input.nextFloat();

2016-2020 Page 37
Advanced Programming in java(16103037)

//initialize the stock type as per user requirement


userStockHoldingArray[i] = new ForeignStockHolding(purchasePrice,
currentPrice, noOfShare, cname, conRate);
//a variable of boolean type
boolean value = true;

//continue loop until user don't command to exit


while(value) //always true
{
System.out.println("Enter your choice : \n 1) Display stock
information with the lowest value\r\n" +
" 2) Display stock with the highest value\r\n" +
" 3) Display the most profitable stock\r\n" +
" 4) Display the least profitable stock\r\n" +
" 5) List all stocks sorted by company name (A-Z)\r\n" +
" 6) List all stocks sorted from the lowest value to the highest
value\r\n" +
" 7) Exit");
//variable to take choice of user
int choice = input.nextInt();
// switch case to choose choice
switch(choice)
{
case 1:
{
displayMinValue(userStockHoldingArray); //display minimum stock value
break;
}
case 2:
{
displayMaxValue(userStockHoldingArray); //display maximum stock value
break;
}
case 3:
{
displayMaxProfitableStock(userStockHoldingArray);
//to display maximum profitable stock from foreign stock
break;
}
case 4:
{
38

displayMinProfitableStock(userStockHoldingArray);
Page

//to display minimum profitable stock

2016-2020 Page 38
Advanced Programming in java(16103037)

break;
}
case 5:
{
displayAscending(userStockHoldingArray);
//method to display ascending order the stack
break;}
case 6:
{
displayInSortedValueOrder(userStockHoldingArray);
//display value in sorted order of foreign stock
break;
}
case 7:
{value = false; //exit case
}
}}
System.out.println("***********************************************");
}}

3.Stock holding.java
package stock;
class StockHolding //a class called StockHolding to
represent a stock that you have purchased
{ /*For instance variables, two floats named purchaseSharePrice
and
*currentSharePrice,
* one int named numberOfShares and
* one string named companyName. */

float purchaseSharePrice, currentSharePrice;


int numberOfShares;
String companyName;

// accessor methods for the instance variables

StockHolding(float purchasePrice, float currentPrice, int


noOfShare, String cname)
{
purchaseSharePrice = purchasePrice;
currentSharePrice = currentPrice;
numberOfShares = noOfShare;
39

companyName = cname;
}
Page

//two other instance methods:

2016-2020 Page 39
Advanced Programming in java(16103037)

float costInDollars()
{
return purchaseSharePrice*numberOfShares;
}

float valueInDollars()
{
return currentSharePrice*numberOfShares;
}
}

Output:
40
Page

2016-2020 Page 40
41
Page
Advanced Programming in java(16103037)

2016-2020 Page 41
42
Page
Advanced Programming in java(16103037)

2016-2020 Page 42
Advanced Programming in java(16103037)

Assignment 7
Problem: Q1. A teacher has five students who have taken four tests. The teacher uses the
following grading scale to assign a letter grade to a student, based on average of hi8s or her four
test scores:
Test Score Letter Grade
90-100 A
80-89 B
70-79 C
60-69 D
0-59 F

Write a class that uses a String array or an ArrayList object to hold five students names, an array
of five characters to hold five students letter grades and five arrays of four doubles each to hold
each students set of test scores.

Q2. ATM Transaction: Using ATM machine, a user can withdraw and deposit money and also
can check balance or print transaction history. Different cases using switch case needs to be
provided for different operations like withdraw, deposit and check balance. The user will choose
from any one of the available options as input. You need to design an ATM class that will throw
an appropriate user defined exception on each transaction.
For example:
a) If number of inter-bank transactions exceeds 3, throw
b) Insufficient balance exception
c) If a user entered wrong pin
…………….
Q3. Lottery Application: Write a Lottery class that simulates a lottery. The class should have
an array of five integers named lotteryNumbers. The constructor should use the Random class to
generate random numbers in range 0 through 9 for each element in the array. The class should
also have a method that accepts an array of five integers that represents a person’s lottery pick.
The method is to compare the corresponding elements in the two arrays and returns the number
of digits that match. For example, the following shows the lotteryNumbers array and the user’s

Code:
43

1.
Page

import java.io.*;

2016-2020 Page 43
Advanced Programming in java(16103037)

//the class storing all the information about student

class studentGrades{
//storing names of students
private String [] studentNames=new String[5];

//storing grades of 5 students


private char [] grades=new char[5];

//storing scores of 4 tests of each of the student


private double [][] scores=new double[5][4];

//storing average test score


private double[] average=new double[5];

//default constructor
studentGrades() {
for(int i=0;i<5;i++) {
studentNames[i]="notdefined";
grades[i]='N';
for(int j=0;j<4;j++) {
scores[i][j]=(double)0;
}
}
}

//setting the values or each student


void SetValue(int std_num) throws IOException {
/**
* Scanner in = new Scanner(System.in);

System.out.println("Enter Name:");
//studentNames[std_num]=in.nextLine();

System.out.println("Enter the scores of 4 tests:");


for(int i=0;i<4;i++)
scores[std_num][i]=in.nextDouble();

in.reset();
in.close();
*/
44

//using buffer reader to read the input


Page

2016-2020 Page 44
Advanced Programming in java(16103037)

BufferedReader input=new BufferedReader(new


InputStreamReader (System.in));

//input of name of student


System.out.println("Enter Name:");
String inputString=input.readLine();
studentNames[std_num]=inputString;

//input of scores
System.out.println("Enter the scores of 4 tests:");
for(int i=0;i<4;i++) {
inputString=input.readLine();

scores[std_num][i]=Double.parseDouble(inputString);

//not accepting test scores less than 0 or greater than 100


do {
if ((scores[std_num][i])<0 || scores[std_num][i]>100) {
System.out.println("SCORES SHOULD BE BETWEEN 0 AND 100");
System.out.println("enter again:");
inputString=input.readLine();
scores[std_num][i]=Double.parseDouble(inputString);
}
}while(scores[std_num][i]<0 ||
scores[std_num][i]>100);
}
}

//calculating average and grades


void calculate(){
for(int i=0;i<5;i++) {
for(int j=0;j<4;j++) {
average[i]=average[i]+scores[i][j];
}
average[i]=average[i]/4;
if(average[i]<=100 && average[i]>=90)
grades[i]='A';
if(average[i]<=89 && average[i]>=80)
grades[i]='B';
if(average[i]<=79 && average[i]>=70)
grades[i]='C';
if(average[i]<=69 && average[i]>=60)
grades[i]='D';
45

if(average[i]<=59 && average[i]>=0)


Page

grades[i]='F';

2016-2020 Page 45
Advanced Programming in java(16103037)

}
}

//get value of each student


void getValue(int std_num) {
//displaying the details of the student
System.out.println("name: "+studentNames[std_num]);
System.out.println("test scores: "+scores[std_num][0]+" "+
scores[std_num][1]+"
"+scores[std_num][2]+"+scores[std_num][3]+"");
System.out.println("average "+average[std_num]);
System.out.println("grade "+grades[std_num]);
}
}
class StudentDetails {

public static void main(String[] args) throws IOException {


studentGrades obj=new studentGrades();
System.out.println("**Student Grading System**");
System.out.println("Enter the details of 5 students:");
for(int i=0;i<5;i++) {
System.out.println("Student"+" "+(i+1));
obj.SetValue(i);
}
obj.calculate();
System.out.println("displaying the details of students");
for(int i=0;i<5;i++) {
System.out.println("Student"+" "+(i+1));
obj.getValue(i);
}
}
}

2. ATM

import java.io.*;

class AtmTransaction{
//as in atm we already have stored accounts along with
//there passwords so i am considering two string arrays storing
//account numbers and their corresponding passwords
46

private String [] accountNumbers=new String[]


Page

{"123","234","345","456","567","678","789","890"};

2016-2020 Page 46
Advanced Programming in java(16103037)

//for convenience keeping passwords same as the account numbers


private String [] passwords=new String[]
{"123","234","345","456","567","678","789","890"};
//int to store the iterator pointing to the account
int pointer;
//balance
double [] balance=new double[]
{2000,3000,5000,7000,6850,4000,8765,9800};
AtmTransaction(){
pointer=0;
}

//to check account number


boolean checkAccNumber(String num) {

//search for this string in the string of account numbers


for(int i=0;i<accountNumbers.length;i++) {
if (num.equals(accountNumbers[i])) {
pointer=i;
return true;
}
}
return false;
}

//to check account password


boolean checkPassword(String pass) {

//search for this string in the string of account numbers


if (pass.equals(passwords[pointer])) {
return true;
}
else
return false;
}

//withdrawing money
void withdraw(double amt) {
if( amt%100==0 || amt%500==0 || amt%2000==0) {
if((balance[pointer]-amt)<0) {
System.out.println("CANNOT WITHDRAW THIS AMOUNT \n"
+"note:amount to be wihdrawn greater than balance ");
}
47

else
Page

balance[pointer]=balance[pointer]-amt;

2016-2020 Page 47
Advanced Programming in java(16103037)

}
else
System.out.println("CANNOT WITHDRAW THIS AMOUNT \n"+"note:amount not
multiple of 100,500,or 2000");
}

//depositing money
void deposit(double amt) {
if(amt>4000) {
System.out.println("CANNOT DEPOSIT MORE THAN
4000");
}
else
balance[pointer]+=amt;
}

//check balance
void checkBalance() {
System.out.println("your current balance is :
"+balance[pointer]);
}

}
public class AtmMachine {
public static void main(String[] args) throws Exception {
//creating object
AtmTransaction object=new AtmTransaction();

//asking for inputs


System.out.println("****ATM TRANSACTION****");
//using Buffer Reader to read
BufferedReader input=new BufferedReader(new
InputStreamReader (System.in));

System.out.println("Enter your account number:");


String accNum=new String();
accNum=input.readLine();

//checking account number


while(!object.checkAccNumber(accNum)) {
System.out.println("ACCOUNT NUMBER INVALID");
System.out.println("Enter your account number:");
accNum=input.readLine();
48

}
Page

2016-2020 Page 48
Advanced Programming in java(16103037)

System.out.println("enter password:");
String pass=new String();
pass=input.readLine();

//checking account password


while(!object.checkPassword(pass)) {
System.out.println("ACCOUNT PASSWORD INVALID");
System.out.println("Enter your account password:");
pass=input.readLine();
}
//switch menu
while(true) {
System.out.println("enter your choice \n"+"1.withdraw"
+"2.deposit"+"3.check balance"+"4.exit()");
String temp=new String();
temp=input.readLine();
int opt=Integer.parseInt(temp);
switch(opt) {
case 1:
System.out.println("enter the amount");
temp=input.readLine();
object.withdraw(Double.parseDouble(temp));
break;
case 2:
System.out.println("enter the amount");
temp=input.readLine();
object.deposit(Double.parseDouble(temp));
break;
case 3:
object.checkBalance();
break;
case 4:
System.exit(0);
default:
System.out.println("THANKS FOR USING ATM");
}
}
}
}

3.Lottary Machine
49

import java.util.*;
Page

class lotterySimulation

2016-2020 Page 49
Advanced Programming in java(16103037)

{
private int []lotteryNumber=new int[5];

/*
* constructor to intialize random lottery numbers
*/

lotterySimulation()
{
Random generator;
for(int i=0;i<5;i++)
{
generator= new Random();
lotteryNumber[i]=i+generator.nextInt(10-i);
}
}

/*
* to compare both array of lottery numbers
*/

int compare(int [] userLotteryNumber)


{
int count=0;
for(int i=0;i<5;i++)
if(lotteryNumber[i]==userLotteryNumber[i])
count++;
return count;
}

void display()
{
System.out.print("Lottery Number is: ");
for(int i=0;i<5;i++)
System.out.print(lotteryNumber[i]);
}

}
public class LotteryApplication {

public static void main(String[] args) {


Scanner input;
/*
50

* to hold user lottery number in array of integer


Page

*/

2016-2020 Page 50
Advanced Programming in java(16103037)

int[] userLotteryNumber=new int[5];


int number;
lotterySimulation Application1 =new lotterySimulation();

/**
* in order to get lottery Number prior to user input,
uncomment the statement below.
*/

Application1.display();
System.out.println("\nEnter your Lottery number one by
one:\t");
for(int i=0;i<5;i++)
{
input=new Scanner(System.in);
number=input.nextInt();
userLotteryNumber[i]=number;
}

if( Application1.compare(userLotteryNumber)==5)
{
System.out.println("\tCongratulation You Won lottery!!!");
Application1.display();
}
else
System.out.println("Sorry only
"+Application1.compare(userLotteryNumber)+" numbers matched");
}
}
Output:
51
Page

2016-2020 Page 51
52
Page
Advanced Programming in java(16103037)

2016-2020 Page 52
53
Page
Advanced Programming in java(16103037)

2016-2020 Page 53
Advanced Programming in java(16103037)

Assignment 8
Problem: n this lab you will design and implement recursive algorithms. The primary focus in
this lab will be algorithms that make a single recursive call. Tail recursion will be explored. An
improved recursive algorithm for computing Fibonacci numbers will be developed. Resources •
Chapter 7: Recursion • Lab6Graphs.pdf – Full size versions of the blank graphs for this lab Java
Files • Count.java • RecursiveFactorial.java • RecursiveFibonacci.java •
RecursiveStringReplace.java • TestFactorial.java • TestFibonacci.java • TestReplace.java •
TimeFibonacci.java
Code:
1.Count:

/**
* countUp - A recursive function that counts up from 1 to n.
*
* @param n The integer value to count up to,
*/
private static void countUp(int n)
{
// IMPLEMENT THIS RECURSIVE METHOD

if(n<=0)
return ;
countUp(n-1); // print value of n
System.out.println(n); //recursive call to countDown by
decrementing n

}
/**
* countDown - A recursive function that counts down from n to 1.
*
* @param n The integer value to count down from.
*/
private static void countDown(int n)
{
// IMPLEMENT THIS RECURSIVE METHOD
if(n<=0)
return;
System.out.println(n); // print value of n
countDown(n-1); //recursive call to countDown by
decrementing n
}
54

2.Recursive Factorial
/**
Page

* The tail recursive version of factorial.

2016-2020 Page 54
Advanced Programming in java(16103037)

*
* @param n The number to compute factorial of.
* @return n factorial.
*/
public long tailRecursive(long n)
{
// IMPLEMENT THIS METHOD USING THE RECURSIVE HELPER FUNCTION
// AND RETURN SOMETHING APPROPRIATE
return helper(n,1); //calling tail recursion
}

/**
* The tail recursive helper function for factorial.
*
* @param n The number to compute factorial of.
* @param partial The partial result that is being built up.
* @return n factorial.
*/

private long helper(long n, long partial)


{
long result = 0;
// IMPLEMENT THIS TAIL RECURSIVE METHOD

if(n<=1) //if n=...-3,-2,-1,0,1


return partial; //return partial
else
return helper(n-1,n*partial); //recursive call
to tail function
}

3. Recursive Fibbonaci
/**
* better - A better version of fibonacci. (Height Limited Double
Recursion)
*
* @param n A positive integer.
* @return The nth fibonacci number.
*/
public long better(long n)
{
55

long result = 0;
// IMPLEMENT THIS RECURSIVE METHOD
Page

if(n<=1)

2016-2020 Page 55
Advanced Programming in java(16103037)

return n;
if (n%2==0)
return (long)Math.pow(better(n/2),2)+2*better(n/2-
1)*better(n/2);
else
return 2*(long)Math.pow(better(n/2),2)+
2*better(n/2)*better(n/2-1)+(long)Math.pow(better(n/2-1), 2);

}
4. Recursive String Replace
/**
* replace - Replace all instances of one character by another.
*
* @param s The string to do the replacement on.
* @param from The character to be replaced.
* @param to the character to change to.
* @return A new string with the appropriate characters
replaced.
*/
public String replace(String s, char from, char to)
{
String result;
if(s=="")
return null;

// IMPLEMENT THIS RECURSIVE METHOD

if(s.length()<1) //if length of string is less than 1

return s; // then return string

else
{
char first;

if(from==s.charAt(0)) //if character exist in string then


first=to; //replace it with to character
else
first=s.charAt(0); //else there is no change in string

return first+replace(s.substring(1),from,to); //recursive


56

call to replace function and adding previous string


Page

2016-2020 Page 56
Advanced Programming in java(16103037)

Output:
Count:

Recursive Factorial:

Recursive Fibbonaci:
57
Page

2016-2020 Page 57
Advanced Programming in java(16103037)

Recursive String Replace:


58
Page

2016-2020 Page 58
Advanced Programming in java(16103037)

Assignment 9
Problem: Link Based Bag Implementation
In this lab you will explore the implementation of the ADT bag using a linked chain. To allow
you to see the difference with the array implementation, the methods you will implement will be
the same as in equals, remove, duplicateAll, and removeDuplicates.
Code:
1.EQUALS:
/** Check to see if two bags are equals.
* @param aBag Another object to check this bag against.
* @return True if the two bags contain the same objects with the
same frequencies.
*/
public boolean equals(LinkedBag<T> aBag) {
boolean result = false; // result of comparison of bags

// COMPLETE THIS METHOD


if(this.numberOfEntries!=aBag.numberOfEntries)
//if size of bags are different they are not equal
return result;
else if(numberOfEntries>0)
{
Node currentnode=this.firstNode;
while(currentnode!=null)
{//calculate frequency of each data and then compare

if(this.getFrequencyOf(currentnode.data)!=aBag.getFrequencyOf(cur
rentnode.data))
{
return result;
}currentnode=currentnode.next;

}result=true;
}
else //if both bags are empty they are equal
result=true;
return result;
} // end equals

2.REMOVE:
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal was successful,
or null. */
59

public T remove() {
T result = null;
Page

2016-2020 Page 59
Advanced Programming in java(16103037)

// MODIFY THIS METHOD TO REMOVE A RANDOM ITEM FROM THE BAG


if(numberOfEntries==0)
return result;//if empty bag then return
int p=(int)(Math.random()*50+1);//generated random number
while(p>numberOfEntries)
{
p=(int)(Math.random()*50+1);//to check if the random number
is in the range
}
int i=1;
Node currentNode=firstNode;
for(;i<p&&currentNode!=null;i++)
{
currentNode=currentNode.next;//currentNode will point to the
random node
}
result=currentNode.data;

if (firstNode != null) {
result = firstNode.data;
firstNode = firstNode.next; // Remove first node from
chain
numberOfEntries--;
} // end if

return result;
} // end remove

3.DUPLICATEALL:
/** Duplicate all the items in a bag.
* @return True if the duplication is possible.
*/
public boolean duplicateAll() {
boolean success = true; // should always return true
// if there is a problem allocating
nodes
// an exception will be thrown

// COMPLETE THIS METHOD


60

if(numberOfEntries==0)
Page

return success;
Node cNode=firstNode;
2016-2020 Page 60
Advanced Programming in java(16103037)

while(cNode!=null)
{
add(cNode.data);//add new node having duplicated data
cNode=cNode.next;
}
return success;
} // end duplicateAll

4.REMOVEDUPLICATE:
/** Remove all duplicate items from a bag
*/
public void removeDuplicates() {

// COMPLETE THIS METHOD


if(numberOfEntries<=1)
return;
LinkedBag<T>tempbag=new LinkedBag<>();//tempbag stores unique
elements
tempbag.add(firstNode.data);
Node currnode;

while(!isEmpty())
{//remove duplicate present of the current node
remove(firstNode.data);//one by one remove node from this
bag
currnode=firstNode;
while(currnode!=null)
{
if(currnode.data==tempbag.firstNode.data)
{
T info=currnode.data;
currnode=currnode.next;
remove(info);
}
else
currnode=currnode.next;
}
if(firstNode!=null)
tempbag.add(this.firstNode.data);//add it to the tempbag
}
currnode=tempbag.firstNode;
while(currnode!=null)
61

{
Page

this.add(currnode.data);

2016-2020 Page 61
Advanced Programming in java(16103037)

currnode=currnode.next;

}//copy tempbag to this bag

return;
}

}
// end removeDuplicates

Output:
62
Page

2016-2020 Page 62
63
Page
Advanced Programming in java(16103037)

2016-2020 Page 63
64
Page
Advanced Programming in java(16103037)

2016-2020 Page 64
65
Page
Advanced Programming in java(16103037)

2016-2020 Page 65
Advanced Programming in java(16103037)

Assignment 10
Problem: List Client
In this lab you will complete two applications that use the Abstract Data Type (ADT) list.
Java Files :
• AList.java • CountingGame.java • ListInterface.java • Primes.java
Counting Game: Suppose we have six players named 1, 2, 3, 4, 5, and 6. Further, suppose the
rhyme has three words A, B, C. There will be five rounds played with one player eliminated in
each round. In the following table, fill in the players next to the part of the rhyme they say in
each round. Cross out the players as they are eliminated. The first round has been completed for
you.
Pieces of the CountingGame class already exist and are in CountingGame.java. Take a look at
that code now if you have not done so already. Also before you start, make sure you are familiar
with the methods available to you in the AList class (check ListInterface.html).
Code:
public class CountingGame
{

public static void main(String args[])


{
ListInterface<Integer> players = null;
ListInterface<String> rhyme = null;

int max;
int position = 1; // always start with the first player

System.out.println("Please enter the number of players.");


max = getInt(" It should be an integer value greater than or
equal to 2.");
System.out.println("Constructing list of players");

// ADD CODE HERE TO CREATE THE LIST OF PLAYERS


players=new AList<Integer>(); //arraylist of players
int i;
for(i=1;i<=max;i++)//code to add players in list
players.add(i);
System.out.println("The players list is " + players);
// ADD CODE HERE TO PLAY THE GAME
rhyme = getRhyme();
i=1;
while(players.getLength()!=1)//Code to remove players from
list
{
66

if(i>players.getLength())
i=i%players.getLength();
Page

i=doRhyme(players,rhyme,i);

2016-2020 Page 66
Advanced Programming in java(16103037)

System.out.println("removing player"+players.getEntry(i));
players.remove(i);
System.out.println("The players list is"+players);
}
System.out.println("The winner is " + players.getEntry(1));
}

/**
* Do the rhyme with the players in the list and remove the
selected
* player.
*
* @param players A list holding the players.
* @param rhyme A list holding the words of the rhyme.
* @param startAt A position to start the rhyme at.
*
* @return The position of the player eliminated.
*/
public static int doRhyme(ListInterface<Integer> players,
ListInterface<String> rhyme, int startAt)
{
// COMPLETE THIS METHOD
int i=1;

System.out.println("player"+players.getEntry(startAt)+""+rhyme.getEntr
y(i));
for(i=2;i<=rhyme.getLength();i++)
{
startAt=1;

System.out.println("player"+players.getEntry(startAt)+""+rhyme.getEntr
y(i));
}
return startAt;

Primes: The skeleton of the Primes class already exists and is in Primes.java. In main declare
and create the candidates list. Add in the values. Print out the candidates list. In main declare
and create the primes and composites lists.Remove the first value from the primes list and
remember it in a variable.Print out the prime that was discovered.Add it to the primes list. Print
67

out all three lists.


Code:
Page

import java.io.*;

2016-2020 Page 67
Advanced Programming in java(16103037)

import java.util.*;

/**
* Primes is a program that will compute prime numbers using the sieve
of Eratosthenes.
*
* @author Charles Hoot
* @version 4.0
*/

public class Primes


{

public static void main(String args[])


{

int max;

System.out.println("Please enter the maximum value to test for


primality");
max = getInt(" It should be an integer value greater than or
equal to 2.");

// COMPLETE THE MAIN


ListInterface<Integer>candidates=new AList<>(); //creating
candidate list
for(int i=2;i<=max;i++)
candidates.add(i);
System.out.println("Candidate list:"+candidates); //printing
candidate list
ListInterface<Integer>primes=new AList<>(); //primes list
ListInterface<Integer>composites=new AList<>(); //primes list
int prime;
while(candidates.getLength()!=0)
{
prime=candidates.getEntry(1);//Removing first entry of list
initially 2 and add it to the primes list
primes.add(prime); candidates.remove(1); //remove from the
candidate list
getComposites(candidates,composites,prime);//generate
composites
System.out.println("candidate list:"+candidates);//printing
68

all the three list


Page

System.out.println("prime list:"+primes);

2016-2020 Page 68
Advanced Programming in java(16103037)

System.out.println("composites list:"+composites);
System.out.println("prime numbers are"+primes);
}

/**
* getComposites - Remove the composite values from possibles list
and
* put them in the composites list.
*
* @param candidates A list of integers holding the possible
values.
* @param composites A list of integers holding the composite
values.
* @param prime An Integer that is prime.
*/
public static void getComposites(ListInterface<Integer>
candidates, ListInterface<Integer> composites, Integer prime)
{
// COMPLETE THIS METHOD
int i;
for(i=1;i<=candidates.getLength();i++)//number having prime as a
factor is added to composite list
{
if(candidates.getEntry(i)%prime==0)
{
composites.add(candidates.getEntry(i));
candidates.remove(i);//removed from candidate list as
well

}
}

Output:
Counting Game:
69
Page

2016-2020 Page 69
Advanced Programming in java(16103037)

Primes:
70
Page

2016-2020 Page 70
Advanced Programming in java(16103037)

Assignment 11
Multithreading
Problem:The Producer–Consumer problem also known as the bounded-buffer problem is
a classic example of a multi-process synchronization problem. The problem describes two
processes, the producer and the consumer, who share a common, fixed-size buffer used as a
queue. The producer's job is to generate data, put it into the buffer, and start again. At the same
time, the consumer is consuming the data (i.e., removing it from the buffer), one piece at a time.
The problem is to make sure that the producer won't try to add data into the buffer if it's full and
that the consumer won't try to remove data from an empty buffer. Implement the solution of this
classical using multi-threading concept in Java.

Code:
Buffer:
package producer_consumer;
public class Buffer
{ int number;
//valueSet tell whether the new value of number is set or
not
boolean valueSet = false;
public synchronized void put (int num)
{ //check if consumer haven't consumed the value then
wait
while(valueSet)
{ try
{ wait(); }
catch(Exception e) {}
}
//set the new value
System.out.println("Put : "+num);
number = num;
valueSet = true;
//notify the consumer thread that value is set
notify();
}
public synchronized void get ()
{ //if value is not set then wait
while(!valueSet)
{ try
{ wait(); }
catch(Exception e) {}
}
//consume the value
71

System.out.println("Get : "+number);
Page

valueSet = false;
//notify the producer thread that value is consumed
2016-2020 Page 71
Advanced Programming in java(16103037)

notify();
}
}

Producer:
package producer_consumer;
public class Producer implements Runnable
{ Buffer b;
public Producer(Buffer b)
{ this.b = b;
//creating and starting the producer thread
Thread t = new Thread(this,"Producer");
t.start();
}
public void run()
{ int i=0;
//set the value
while(true)
{ b.put(i++);
try
{ Thread.sleep(1000); }
catch(Exception e) {}
}
}
}

Consumer:
package producer_consumer;
public class Consumer implements Runnable
{ Buffer b;
public Consumer(Buffer b)
{ this.b = b;
//creating and starting the consumer thread
Thread t = new Thread(this,"Consumer");
t.start();
}
public void run()
{ //consume the value
while(true)
{ b.get();
try
72

{ Thread.sleep(1000); }
catch(Exception e) {}
Page

2016-2020 Page 72
Advanced Programming in java(16103037)

}
}

Main method:
package producer_consumer;
public class Main
{ public static void main(String a[])
{ Buffer b = new Buffer();
//anonymous object of producer and consumer
new Producer(b);
new Consumer(b);
}
}

Output:
73
Page

2016-2020 Page 73

Você também pode gostar