Java File Lab
Java File Lab
Jul-Dec, 2018
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
2016-2020 Page 2
Advanced Programming in java(16103037)
Introduction
1.Java
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.
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.
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)
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 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.
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).
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)
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).
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
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.
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.
2016-2020 Page 8
Advanced Programming in java(16103037)
Assignment 1
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
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++; }
2016-2020 Page 10
Advanced Programming in java(16103037)
2016-2020 Page 11
12
Page
Advanced Programming in java(16103037)
2016-2020 Page 12
Advanced Programming in java(16103037)
Assignment 2
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
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)
2016-2020 Page 15
Advanced Programming in java(16103037)
Assignment 3
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
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) {
}
Page
2016-2020 Page 24
Advanced Programming in java(16103037)
return data;
}
Output:
25
Page
2016-2020 Page 25
Advanced Programming in java(16103037)
Assignment 5
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)
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)
"+array[i].purchaseSharePrice);
Page
2016-2020 Page 32
Advanced Programming in java(16103037)
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];
if((temp.valueInDollars()-temp.costInDollars()) >
(array[i].valueInDollars()-array[i].costInDollars()))
34
Page
2016-2020 Page 34
Advanced Programming in java(16103037)
2016-2020 Page 35
Advanced Programming in java(16103037)
//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
2016-2020 Page 36
Advanced Programming in java(16103037)
conRate = input.nextFloat();
2016-2020 Page 37
Advanced Programming in java(16103037)
displayMinProfitableStock(userStockHoldingArray);
Page
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. */
companyName = cname;
}
Page
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)
class studentGrades{
//storing names of students
private String [] studentNames=new String[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;
}
}
}
System.out.println("Enter Name:");
//studentNames[std_num]=in.nextLine();
in.reset();
in.close();
*/
44
2016-2020 Page 44
Advanced Programming in java(16103037)
//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);
grades[i]='F';
2016-2020 Page 45
Advanced Programming in java(16103037)
}
}
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
{"123","234","345","456","567","678","789","890"};
2016-2020 Page 46
Advanced Programming in java(16103037)
//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();
}
Page
2016-2020 Page 48
Advanced Programming in java(16103037)
System.out.println("enter password:");
String pass=new String();
pass=input.readLine();
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
*/
void display()
{
System.out.print("Lottery Number is: ");
for(int i=0;i<5;i++)
System.out.print(lotteryNumber[i]);
}
}
public class LotteryApplication {
*/
2016-2020 Page 50
Advanced Programming in java(16103037)
/**
* 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
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.
*/
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;
else
{
char first;
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)
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
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)
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
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() {
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;
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
{
int max;
int position = 1; // always start with the first player
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
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
*/
int max;
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