Practical Solution
Practical Solution
Practical Solution
Practical 1:
Write a JAVA Program to implement built-in support (java.util.Observable) Weather station with
members temperature, humidity, pressure and methods mesurmentsChanged(),
setMesurment(), getTemperature(), getHumidity(),getPressure()
DisplayElement.java:
Observer.java:
Subject.java:
WeatherData.java:
import java.util.*;
public class WeatherData implements Subject
{
private ArrayList<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData()
{
observers = new ArrayList<>();
}
public void registerObserver(Observer o)
{
observers.add(o);
}
public void removeObserver(Observer o)
{
int i = observers.indexOf(o);
if (i >= 0)
{
observers.remove(i);
}
}
public void notifyObservers()
{
for (int i = 0; i < observers.size(); i++)
{
Observer observer = (Observer)observers.get(i);
observer.update(temperature, humidity, pressure);
}
}
public void measurementsChanged()
{
notifyObservers();
}
public void setMeasurements(float temperature, float humidity, float pressure)
{
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
public float getTemperature()
{
return temperature;
}
public float getHumidity()
{
return humidity;
}
public float getPressure()
{
return pressure;
}
}
ForecastDisplay.java:
StatisticsDisplay.java
class StatisticsDisplay implements Observer, DisplayElement
{
private float maxTemp = 0.0f;
private float minTemp = 200;
private float tempSum= 0.0f;
private int numReadings;
private WeatherData weatherData;
public StatisticsDisplay(WeatherData weatherData)
{
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float temp, float humidity, float pressure)
{
tempSum += temp;
numReadings++;
if (temp > maxTemp)
{
maxTemp = temp;
}
if (temp < minTemp)
{
minTemp = temp;
}
display();
}
public void display()
{
System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings)+
"/" + maxTemp + "/" + minTemp);
}
}
CurrentConditionsDisplay.java:
WeatherStation.java:
class WeatherStation
{
public static void main(String[] args)
{
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay=new
CurrentConditionsDisplay(weatherData);
StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);
ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);
/*
Output:
D:\MScSem3Practicals\SADP Pract Assignment\Pract1>javac WeatherData.java
*/
Practical 2:
Write a Java Program to implement I/O Decorator for converting uppercase letters to lower case
letters.
LowerCaseInputStream.java
import java.io.*;
public class LowerCaseInputStream extends FilterInputStream
{
public LowerCaseInputStream(InputStream in)
{
super(in);
}
public int read() throws IOException
{
int c = super.read();
return (c == -1 ? c : Character.toLowerCase((char)c));
}
public int read(byte[] b, int offset, int len) throws IOException
{
int result = super.read(b, offset, len);
for (int i = offset; i < offset+result; i++)
{
b[i] = (byte)Character.toLowerCase((char)b[i]);
}
return result;
}
}
InputTest.java:
import java.io.*;
public class InputTest
{
public static void main(String[] args) throws IOException
{
int c;
try
{
InputStream in = new LowerCaseInputStream(new BufferedInputStream(new
FileInputStream("test.txt")));
while((c = in.read()) >= 0)
{
System.out.print((char)c);
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/*
Input: test.txt:
Hello
How are YOU!!?
Output:
D:\MScSem3Practicals\SADP Pract Assignment\Pract2>java InputTest
hello
how are you!!?
D:\MScSem3Practicals\SADP Pract Assignment\Pract2>
*/
Practical 3:
Write a Java Program to implement Factory method for Pizza Store with createPizza(),
orederPizza(), prepare(), Bake(), cut(), box(). Use this to create variety of pizza’s like
NyStyleCheesePizza, ChicagoStyleCheesePizza etc.
PizzaFactoryDemo.java:
import java.util.ArrayList;
abstract class Pizza
{
String name;
String dough;
String sauce;
ArrayList toppings = new ArrayList();
void prepare()
{
System.out.println("Preparing " + name);
System.out.println("Tossing dough...");
System.out.println("Adding sauce...");
System.out.println("Adding toppings: ");
for (int i = 0; i < toppings.size(); i++)
{
System.out.println(" " + toppings.get(i));
}
}
void bake()
{
System.out.println("Bake for 25 minutes at 350");
}
void cut()
{
System.out.println("Cutting the pizza into diagonal slices");
}
void box()
{
System.out.println("Place pizza in official PizzaStore box");
}
public String getName()
{
return name;
}
public String toString()
{
StringBuffer display = new StringBuffer();
display.append("---- " + name + " ----\n");
display.append(dough + "\n");
display.append(sauce + "\n");
for (int i = 0; i < toppings.size(); i++)
{
display.append((String )toppings.get(i) + "\n");
}
return display.toString();
}
}
/*
Output:
*/
Practical 4:
Write a Java Program to implement Singleton pattern for multithreading.
ChocolateControllerDemo.java:
class ChocolateBoiler
{
private boolean empty;
private boolean boiled;
private static ChocolateBoiler uniqueInstance;
private ChocolateBoiler()
{
empty = true;
boiled = false;
}
ChocolateControllerDemo.java:
/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.
*/
Practical 5:
Write a Java Program to implement command pattern to test Remote Control.
RemoteControlTest.java
interface Command
{
public void execute();
}
class Light
{
public void on()
{
System.out.println("Light is on");
}
public void off()
{
System.out.println("Light is off");
}
}
class LightOnCommand implements Command
{
Light light;
class Stereo
{
public void on()
{
System.out.println("Stereo is on");
}
public void off()
{
System.out.println("Stereo is off");
}
public void setCD()
{
System.out.println("Stereo is set " +"for CD input");
}
public void setDVD()
{
System.out.println("Stereo is set"+" for DVD input");
}
public void setRadio()
{
System.out.println("Stereo is set" +" for Radio");
}
public void setVolume(int volume)
{
System.out.println("Stereo volume set"+ " to " + volume);
}
}
class SimpleRemoteControl
{
Command slot;
public SimpleRemoteControl()
{
}
// Driver class
class RemoteControlTest
{
public static void main(String[] args)
{
SimpleRemoteControl remote =new SimpleRemoteControl();
Light light = new Light();
Stereo stereo = new Stereo();
remote.setCommand(new LightOnCommand(light));
remote.buttonWasPressed();
remote.setCommand(new StereoOnWithCDCommand(stereo));
remote.buttonWasPressed();
remote.setCommand(new StereoOffCommand(stereo));
remote.buttonWasPressed();
}
}
/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.
RemoteLoader.java:
remoteControl.onButtonWasPushed(0);
remoteControl.offButtonWasPushed(0);
System.out.println(remoteControl);
remoteControl.undoButtonWasPushed();
remoteControl.onButtonWasPushed(1);
System.out.println(remoteControl);
remoteControl.undoButtonWasPushed();
}
}
/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.
*/
RemoteControlWithUndo.java:
import java.util.*;
public class RemoteControlWithUndo {
Command[] onCommands;
Command[] offCommands;
Command undoCommand;
public RemoteControlWithUndo() {
onCommands = new Command[7];
offCommands = new Command[7];
CeilingFanOffCommand.java:
CeilingFanMediumCommand.java:
CeilingFanLowCommand.java:
CeilingFanHighCommand.java:
CeilingFan.java
Command.java:
NoCommand.java:
EnumerationIterator.java
import java.util.*;
public class EnumerationIterator implements Iterator {
Enumeration enumeration;
EnumerationIteratorTestDrive.java:
import java.util.*;
public class EnumerationIteratorTestDrive
{
public static void main (String args[])
{
Vector v = new Vector(Arrays.asList(args));
Iterator iterator = new EnumerationIterator(v.elements());
while (iterator.hasNext())
{
System.out.println(iterator.next());
}
}
}
/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.
MenuTestDrive.java:
import java.util.*;
public class MenuTestDrive
{
public static void main(String args[])
{
PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
DinerMenu dinerMenu = new DinerMenu();
Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu);
waitress.printMenu();
waitress.printVegetarianMenu();
}
}
/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.
LUNCH
Vegetarian BLT, 2.99 -- (Fakin') Bacon with lettuce & tomato on whole wheat
BLT, 2.99 -- Bacon with lettuce & tomato on whole wheat
Soup of the day, 3.29 -- Soup of the day, with a side of potato salad
Hotdog, 3.05 -- A hot dog, with saurkraut, relish, onions, topped with cheese
Steamed Veggies and Brown Rice, 3.99 -- Steamed vegetables over brown rice
Pasta, 3.89 -- Spaghetti with Marinara Sauce, and a slice of sourdough bread
VEGETARIAN MENU
----
BREAKFAST
K&B's Pancake Breakfast 2.99
Pancakes with scrambled eggs, and toast
Blueberry Pancakes 3.49
Pancakes made with fresh blueberries, and blueberry syrup
Waffles 3.59
Waffles, with your choice of blueberries or strawberries
LUNCH
Vegetarian BLT 2.99
(Fakin') Bacon with lettuce & tomato on whole wheat
Steamed Veggies and Brown Rice 3.99
Steamed vegetables over brown rice
Pasta 3.89
Spaghetti with Marinara Sauce, and a slice of sourdough bread
import java.util.Iterator;
public interface Menu
{
public Iterator createIterator();
}
MenuItem.java:
public class MenuItem
{
String name;
String description;
boolean vegetarian;
double price;
import java.util.Iterator;
public class DinerMenu implements Menu
{
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems;
public DinerMenu()
{
menuItems = new MenuItem[MAX_ITEMS];
DinerMenuIterator.java:
import java.util.Iterator;
public class DinerMenuIterator implements Iterator
{
MenuItem[] list;
int position = 0;
PancakeHouseMenu.java:
import java.util.ArrayList;
import java.util.Iterator;
public class PancakeHouseMenu implements Menu
{
ArrayList menuItems;
public PancakeHouseMenu()
{
menuItems = new ArrayList();
addItem("K&B's Pancake Breakfast","Pancakes with scrambled eggs, and
toast",true,2.99);
addItem("Regular Pancake Breakfast","Pancakes with fried eggs,
sausage",false,2.99);
addItem("Blueberry Pancakes","Pancakes made with fresh blueberries, and
blueberry syrup",true,3.49);
addItem("Waffles","Waffles, with your choice of blueberries or
strawberries",true,3.59);
}
Waitress.java:
import java.util.Iterator;
public class Waitress
{
Menu pancakeHouseMenu;
Menu dinerMenu;
System.out.println("MENU\n----\nBREAKFAST");
printMenu(pancakeIterator);
System.out.println("\nLUNCH");
printMenu(dinerIterator);
}
GumballMachineTestDrive.java:
System.out.println(gumballMachine);
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
System.out.println(gumballMachine);
gumballMachine.insertQuarter();
gumballMachine.ejectQuarter();
gumballMachine.turnCrank();
System.out.println(gumballMachine);
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
gumballMachine.ejectQuarter();
System.out.println(gumballMachine);
gumballMachine.insertQuarter();
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
System.out.println(gumballMachine);
}
}
/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.
*/
GumballMachine.java:
HeartModel.java:
package djview;
import java.util.*;
public class HeartModel implements HeartModelInterface, Runnable
{
ArrayList beatObservers = new ArrayList();
ArrayList bpmObservers = new ArrayList();
int time = 1000;
int bpm = 90;
Random random = new Random(System.currentTimeMillis());
Thread thread;
public HeartModel()
{
thread = new Thread(this);
thread.start();
}
public void run()
{
int lastrate = -1;
for(;;)
{
int change = random.nextInt(10);
if (random.nextInt(2) == 0)
{
change = 0 - change;
}
int rate = 60000/(time + change);
if (rate < 120 && rate > 50)
{
time += change;
notifyBeatObservers();
if (rate != lastrate)
{
lastrate = rate;
notifyBPMObservers();
}
}
try
{
Thread.sleep(time);
}
catch (Exception e)
{}
}
}
public int getHeartRate()
{
return 60000/time;
}
public void registerObserver(BeatObserver o)
{
beatObservers.add(o);
}
public void removeObserver(BeatObserver o)
{
int i = beatObservers.indexOf(o);
if (i >= 0)
{
beatObservers.remove(i);
}
}
public void notifyBeatObservers()
{
for(int i = 0; i < beatObservers.size(); i++)
{
BeatObserver observer = (BeatObserver)beatObservers.get(i);
observer.updateBeat();
}
}
public void registerObserver(BPMObserver o)
{
bpmObservers.add(o);
}
public void removeObserver(BPMObserver o)
{
int i = bpmObservers.indexOf(o);
if (i >= 0)
{
bpmObservers.remove(i);
}
}
public void notifyBPMObservers()
{
for(int i = 0; i < bpmObservers.size(); i++)
{
BPMObserver observer = (BPMObserver)bpmObservers.get(i);
observer.updateBPM();
}
}
}
BeatModel.java:
package djview;
import javax.sound.midi.*;
import java.util.*;
public class BeatModel implements BeatModelInterface, MetaEventListener
{
Sequencer sequencer;
ArrayList beatObservers = new ArrayList();
ArrayList bpmObservers = new ArrayList();
int bpm = 90;
Sequence sequence;
Track track;
public void initialize()
{
setUpMidi();
buildTrackAndStart();
}
public void on()
{
sequencer.start();
setBPM(90);
}
public void off()
{
setBPM(0);
sequencer.stop();
}
public void setBPM(int bpm)
{
this.bpm = bpm;
sequencer.setTempoInBPM(getBPM());
notifyBPMObservers();
}
void beatEvent()
{
notifyBeatObservers();
}
public void registerObserver(BeatObserver o)
{
beatObservers.add(o);
}
public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick)
{
MidiEvent event = null;
try
{
ShortMessage a = new ShortMessage();
a.setMessage(comd, chan, one, two);
event = new MidiEvent(a, tick);
}
catch(Exception e)
{
e.printStackTrace();
}
return event;
}
}
BeatController.java:
package djview;
public class BeatController implements ControllerInterface
{
BeatModelInterface model;
DJView view;
package djview;
public class BeatBar extends JProgressBar implements Runnable
{
JProgressBar progressBar;
Thread thread;
public BeatBar()
{
thread = new Thread(this);
setMaximum(100);
thread.start();
}
public void run()
{
for(;;)
{
int value = getValue();
value = (int)(value * .75);
setValue(value);
repaint();
try
{
Thread.sleep(50);
}
catch (Exception e) {};
}
}
}
HeartModelInterface.java:
package djview;
public interface HeartModelInterface
{
int getHeartRate();
void registerObserver(BeatObserver o);
void removeObserver(BeatObserver o);
void registerObserver(BPMObserver o);
void removeObserver(BPMObserver o);
}
BeatModelInterface.java:
package djview;
public interface BeatModelInterface
{
void initialize();
void on();
void off();
void setBPM(int bpm);
int getBPM();
void registerObserver(BeatObserver o);
void removeObserver(BeatObserver o);
void registerObserver(BPMObserver o);
void removeObserver(BPMObserver o);
}
ControlIerInterface.java:
package djview;
public interface ControllerInterface
{
void start();
void stop();
void increaseBPM();
void decreaseBPM();
void setBPM(int bpm);
}
BPMObserver.java
package djview;
public interface BPMObserver
{
void updateBPM();
}
BeatObserver.java:
package djview;
public interface BeatObserver
{
void updateBeat();
}
HeartTestDrive.java:
package djview;
public class HeartTestDrive
{
public static void main (String[] args)
{
HeartModel heartModel = new HeartModel();
ControllerInterface model = new HeartController(heartModel);
}
}
DJTestDrive.java:
package djview;
public class DJTestDrive
{
public static void main (String[] args)
{
BeatModelInterface model = new BeatModel();
ControllerInterface controller = new BeatController(model);
}
}
Output: