Vehicle.java
public class Vehicle
{
//Declaring instance variables
private int max_no_passengers;
private int top_speed;
private double miles_travelled;
//Parameterized constructor
public Vehicle(int max_no_passengers, int top_speed, double miles_travelled) {
super();
this.max_no_passengers = max_no_passengers;
this.top_speed = top_speed;
this.miles_travelled = miles_travelled;
}
//Getters and setters
public int getMax_no_passengers() {
return max_no_passengers;
}
public void setMax_no_passengers(int max_no_passengers) {
this.max_no_passengers = max_no_passengers;
}
public int getTop_speed() {
return top_speed;
}
public void setTop_speed(int top_speed) {
this.top_speed = top_speed;
}
public double getMiles_travelled() {
return miles_travelled;
}
public void setMiles_travelled(double miles_travelled) {
this.miles_travelled = miles_travelled;
}
/* This getInfor() method returns the information about this vehicle class object
* Params: void
* Return:String
*/
public String getInfo()
{
String str=\"\ Maximum No of Passengers :\"+getMax_no_passengers()+
\"\ Top Speed :\"+getTop_speed()+
\"\ Total Miles Travelled :\"+getMiles_travelled();
return str;
}
}
_____________________________________________
FoodTruck.java
import java.util.ArrayList;
public class FoodTruck extends Vehicle{
//Declaring instance variables
private String name;
private ArrayList menu;
//Parameterized constructor
public FoodTruck(int max_no_passengers, int top_speed,
double miles_travelled, String name, ArrayList menu) {
super(max_no_passengers, top_speed, miles_travelled);
this.name = name;
this.menu = menu;
}
//Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList getMenu() {
return menu;
}
public void setMenu(ArrayList menu) {
this.menu = menu;
}
/* This getInfor() method returns the information about this Food truck class Object
* And also the information about the Vehicle class Object.
* Params: void
* Return:String
*/
@Override
public String getInfo() {
String str=\"Food Truck Name : \"+name+
\"\ Menu of items : \"+menu+super.getInfo();
return str;
}
}
________________________________________________
Test.java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//Creating an ArrayList Object which holds List of Menu Items
ArrayList menu1=new ArrayList();
//Adding menu items to the ArrayList
menu1.add(\"Burger\");
menu1.add(\"Pizza\");
menu1.add(\"Chips\");
//Creating FoodTruck Object by passing parameters.
FoodTruck truck1=new FoodTruck(15,100,10000,\"Mobile Food Court\",menu1);
//Displaying the Truck1 Information.
System.out.println(\"__________Truck 1 Details__________\");
System.out.println(truck1.getInfo());
//Creating an ArrayList Object which holds List of Menu Items
ArrayList menu2=new ArrayList();
//Adding menu items to the ArrayList
menu2.add(\"Tea\");
menu2.add(\"Coffe\");
menu2.add(\"Cool Drinks\");
//Creating FoodTruck Object by passing parameters.
Write a program that mimics the operations of several vending machin.pdfeyebolloptics
Write a program that mimics the operations of several vending machines. More specifically, the
program simulates what happens when the user chooses one of the vending machines, inputs
money and picks an item from the vending machine. Assume there are two vending machines:
one for drinks and one for snacks. Each vending machine contains several items. The name,
price, and quantity of each item is given in two text files; one named “drinks.txt” for the drinks
vending machine and the other named “snacks.txt” for the snacks vending machine.
The format of the input values is comma-separated. The items listed should be organized in the
file with the following order: name, price, quantity. Here are some example items:
The actual reading and parsing of the input file is already handled in the class supplied to you
(see code on BlackBoard). You are given the variables as individual values. You will need to
create the .txt files for creating and testing your vending machines.
You will need to create/complete three classes for this homework assignment: Item,
VendingMachine, and VendingMachineDriver.
Problem Description
Milk,2.00,1
Within your VendingMachine class, include these methods:
VendingMachineThisconstructormethodwilltakeinthenameoftheinputfileand create a vending
machine object. A vending machine object will contain an array of Item objects called stock and
an amount of revenue earned. This constructor method has been completed for you and should
work appropriately once you have completed the rest of this class and the other class definitions.
vendThismethodwillsimulatethevendingtransactionafteravalidamountofmoney and an item
selection are entered. This method will decide if the transaction is successful (enough money or
item) and update the vending machine appropriately.
outputMessage This method will print an appropriate message depending on the success of the
transaction. If the user does not have enough money to buy the chosen item, the vending machine
should prompt the user to enter more money or exit the machine. If the vending machine is out of
the chosen item, the program will print an apology message and prompt the user to choose
another item or exit the machine. If there is enough money for the item selected, then the
vending machine will give the user the item and return the change.
printMenuThismethodprintsthemenuofitemsforthechosenvendingmachine. The Item class needs
to include the following data variables:
• description as a String
• price as a double
• quantity as an int
Within your VendingMachineDriver class, include a main method as the starting point for your
solution that creates the vending machine objects appropriately and then use a loop that
continues interacting with the vending machines until the user enters “X” to exit. See the sample
session for details.
As you implement your solution, you might find that some methods contain some repeated
coding logic. To avoid unnecessary redundancies in your code, have these method.
Production.javapublic class Production { Declaring instance.pdfsooryasalini
Production.java
public class Production {
//Declaring instance variables
private String title;
private String director;
private String writer;
//Parameterized constructor
public Production(String title, String director, String writer) {
super();
this.title = title;
this.director = director;
this.writer = writer;
}
//Setters and getters.
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
//display() method which displays the Instance variable values
public void display()
{
System.out.println(\"Title: \" + this.title);
System.out.println(\"Director: \" + this.director);
System.out.println(\"Writer: \" + this.writer);
}
//toString() method is used to display the contents of an object
@Override
public String toString() {
return \"Title :\" + title + \"\ Director :\" + director
+ \"\ Writer :\" + writer;
}
}
___________________________________________
Film.java
public class Film extends Production{
//Declaring instance variables
private int boxOfficeGross;
//Parameterized constructor
public Film(String title, String director, String writer, int boxOfficeGross) {
super(title, director, writer);
this.boxOfficeGross = boxOfficeGross;
}
//Setters and getters.
public int getBoxOfficeGross() {
return boxOfficeGross;
}
public void setBoxOfficeGross(int boxOfficeGross) {
this.boxOfficeGross = boxOfficeGross;
}
//display() method which displays the Instance variable values
public void display()
{
System.out.println(\"BoxOfiiceGross: \" + this.boxOfficeGross);
}
//toString() method is used to display the contents of an object
@Override
public String toString() {
return super.toString()+\"\ BoxOfficeGross :\" + boxOfficeGross+\"\ \";
}
}
_______________________________________________
Play.java
public class Play extends Production {
//Declaring instance variables
private int performances;
//Parameterized constructor
public Play(String title, String director, String writer, int performances) {
super(title, director, writer);
this.performances = performances;
}
//Setters and getters.
public int getPerformances() {
return performances;
}
public void setPerformances(int performances) {
this.performances = performances;
}
//display() method which displays the Instance variable values
public void display()
{
System.out.println(\"Performances: \" + this.performances);
}
//toString() method is used to display the contents of an object
@Override
public String toString() {
return super.toString()+\"\ Performances :\" + performances+\"\ \";
}
}
_______________________________________________
Musical.java
public class BobsTerribleTests
{
public static void main(String[] args)
{
//Creating an Film Object by passing parameters
Film titanic = new Film(\"Titanic\", \"James Cameron\", \"James Cameron\.
For the following questions, you will implement the data structure to.pdfarjunhassan8
For the following questions, you will implement the data structure to store information used by a
local car dealer. Each car has some information and stored in a text files called cars: Write a
main program for all questions to let the user enter, delete, search for information, and print
current cars stored in the data structure. Cars formatted so car records separated by a blank line.
Each record contains (in order, each in a single line): Make (manufacturer). Model, Year,
Mileage, Price. Implement a double linked-list to store cars data. Write a double linked-list class
including search, delete, append (to the head and tail), and remove (from the head and tail).
Implement a FIFO queue of car data using the double linked-list. You can use the double linked
list you wrote in Q1. Implement a max-heap of cars data that can extract the car with the highest
price. Write a max-heap class including heapify, build heap, extract, and insertion. Implement a
binary search tree of car data. Write a BST class including search, insertion, and deletion.
Solution
Cars.java
package pacages;
public class Cars {
String make;
String model;
int year;
double mileage;
double price;
// Setters and getters for the Cars member variables
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getMileage() {
return mileage;
}
public void setMileage(double mileage) {
this.mileage = mileage;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString()
{
return \"Make: \"+getMake()+ \" Model: \"+getModel()+ \" Year: \"+getYear() + \"
Mileage: \"+getMileage() + \" Price: \"+getPrice();
}
}
DoublyLinkedList.java
package pacages;
class Node
{
protected Cars data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = null;
}
/* Constructor */
public Node(Cars d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev()
{
return prev;
}
/* Function to set data to node */
public void setData(Cars d)
{
data = d;
}
/* Function to get data from node */
public Cars getData()
{
return data;
}
}
/* Class linkedList */
public class DoublyLinkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public DoublyLinkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of list */
public.
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
Creat Shape classes from scratch DETAILS You will create 3 shape classes (Circle, Rectangle,
Triangle) that all inherit from a single abstract class called AbstractShape which implements
Shape (also created by you). You are also responsible for creating the driver class
\"Assignment7.java\" (program that tests your classes and described on page 3) which does the
following reads input data from a file instantiates various objects of the three shapes based on the
input data stores each in a LinkedList outputs this list to an output file sorts a \"copy\" of this
LinkedList of objects outputs the sorted version of the list to the output file outputs the original
list to the output file This driver program also needs to \"ignore errors in the input file that breach
the specified input format as described in the Assianment7,java details (see page 3 1. Shape.java
This is an interface that has 2 abstract methods, and passes the responsibility of implementing the
compareTo method to the class that implements Shape (you may note, nomally Comparable is
\"implemented\" by a class. However, an interface cannot implement because interfaces can only
contain abstract methods. That said, an interface can only extend other interfaces and the
responsibility of actually \"implementing\" the abstract method(s) of the super class interface is
passed on to the sub-classes) public interface Shape extends Comparable public double
calculateAreal) Il This abstract method is implemented at the concrete level public Shape
copyShape); Il also implemented at the concrete level 2. AbstractShape.java public abstract class
AbstractShape implements Shape This class should contain an instance field to store the name of
each obiect. The constructor which sets this field should receive the name and a number to be
concatenated to the name and then stored in the name field Recall, when the super class has a
parameterized constructor, the sub-classes will need to call it AND the sub- classes will need to
also provide a constructor without parameters This abstract class will implement the compareTo
method passed on from the Shape interface and will pass on the responsibility of implementing
calculateArea to the extending sub-classes (compare To will use the calculateArea method when
comparing 2 Shape objects). Along with compare To, one more concrete method should be
included. The following will be used by the sub-classes\' toString method: public String
getName) II Simply returns the name field data
Solution
in7.txt
4.4
2.5 3
8.1 3.0 5.0
2.5 3 4
2.5
tuesday
-7
1.0
3 three
3 -9
3 5
1.0
Assignment7.java
import java.io.*;
import java.util.*;
public class Assignment7 {
/**
* This is the test driver class that will include main.
* This program MUST read a file named in7.txt and
* generate an output file named out7.txt. The in7.txt
* file must be created by you based on formatting
* described shortly.
*
* @param theArgs
*/
public static void main(String[] theArgs) {
List myList = new Arra.
operating system linux,ubuntu,Mac Geometri.pdfaquadreammail
//operating system linux,ubuntu,Mac
/*********************GeometricObject.java**********************/
public abstract class GeometricObject {
private String color = \"white\";
private boolean filled;
// default constructure
public GeometricObject() {
super();
// TODO Auto-generated constructor stub
}
// construct a Geometric Object
// parameterized constructure
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
/** Getter method for color */
public String getColor() {
return color;
}
/** Setter method for color */
public void setColor(String color) {
this.color = color;
}
/**
* Getter method for filled. Since filled is boolean, so the gret method
* name is isFilled
*/
public boolean isFilled() {
return filled;
}
/** Setter method for filled */
public void setFilled(boolean filled) {
this.filled = filled;
}
/** Abstract method for FindArea */
public abstract double findArea();
/** Abstract method for findPerimeter */
public abstract double findPerimeter();
}
/*****************************Octagon.java**************/
public class Octagon extends GeometricObject implements Cloneable, Comparable {
private double side;
/** construct a Octagon with specified side */
public Octagon(double side) {
super();
this.side = side;
}
/** Implement the abstract method findArea in GeometricObject */
@Override
public double findArea() {
double area = (2 + 4 / Math.sqrt(2)) * side * side;
return area;
}
/** Implement the abstract method findArea in findPerimeter */
@Override
public double findPerimeter() {
double perimeter = 8 * side;
return perimeter;
}
/** Implement the compareTo method in Comparable interface */
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/*******************App.java*******************/
public class App {
public static void main(String[] args) {
Octagon a1 = new Octagon(5);//creating object of octagon
System.out.println(\"Area of a1 is \" + a1.findArea());
System.out.println(\"Perimeter of a1 is \" + a1.findPerimeter());
Object a2;
try {
a2 = a1.clone();
String result = (a1.compareTo(a2) == 0) ? \"a1 and its clone a2 have the same area\"
: \"a1 and its clone a2 have different areas\";
System.out.println(\"Compare a1 and its clone a2:\ \\t \" + result);
System.out.println(\"Hashcode of a1: \" + a1.hashCode());
System.out.println(\"Hashcode of a2: \" + a2.hashCode());
System.out.println(\"Displaying a1: \" + a1);
System.out.println(\"Displaying a2: \" + a2);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
/*****************output***************/
gopal@gopal:~/Desktop/chegg$ javac GeometricObject.java
gopal@gopal:~/Desktop/chegg$ javac Octagon.java
gopal@gopal:~/Desktop/chegg$ javac App.java
gopal@gopal:~/Desktop/chegg$ java App
Area of a1 is 120.71067811865476
Perimeter of a1 is 40.0
Compare a1 and its clone a2:
a1 and its clone a2 have the same area
.
Write a program that mimics the operations of several vending machin.pdfeyebolloptics
Write a program that mimics the operations of several vending machines. More specifically, the
program simulates what happens when the user chooses one of the vending machines, inputs
money and picks an item from the vending machine. Assume there are two vending machines:
one for drinks and one for snacks. Each vending machine contains several items. The name,
price, and quantity of each item is given in two text files; one named “drinks.txt” for the drinks
vending machine and the other named “snacks.txt” for the snacks vending machine.
The format of the input values is comma-separated. The items listed should be organized in the
file with the following order: name, price, quantity. Here are some example items:
The actual reading and parsing of the input file is already handled in the class supplied to you
(see code on BlackBoard). You are given the variables as individual values. You will need to
create the .txt files for creating and testing your vending machines.
You will need to create/complete three classes for this homework assignment: Item,
VendingMachine, and VendingMachineDriver.
Problem Description
Milk,2.00,1
Within your VendingMachine class, include these methods:
VendingMachineThisconstructormethodwilltakeinthenameoftheinputfileand create a vending
machine object. A vending machine object will contain an array of Item objects called stock and
an amount of revenue earned. This constructor method has been completed for you and should
work appropriately once you have completed the rest of this class and the other class definitions.
vendThismethodwillsimulatethevendingtransactionafteravalidamountofmoney and an item
selection are entered. This method will decide if the transaction is successful (enough money or
item) and update the vending machine appropriately.
outputMessage This method will print an appropriate message depending on the success of the
transaction. If the user does not have enough money to buy the chosen item, the vending machine
should prompt the user to enter more money or exit the machine. If the vending machine is out of
the chosen item, the program will print an apology message and prompt the user to choose
another item or exit the machine. If there is enough money for the item selected, then the
vending machine will give the user the item and return the change.
printMenuThismethodprintsthemenuofitemsforthechosenvendingmachine. The Item class needs
to include the following data variables:
• description as a String
• price as a double
• quantity as an int
Within your VendingMachineDriver class, include a main method as the starting point for your
solution that creates the vending machine objects appropriately and then use a loop that
continues interacting with the vending machines until the user enters “X” to exit. See the sample
session for details.
As you implement your solution, you might find that some methods contain some repeated
coding logic. To avoid unnecessary redundancies in your code, have these method.
Production.javapublic class Production { Declaring instance.pdfsooryasalini
Production.java
public class Production {
//Declaring instance variables
private String title;
private String director;
private String writer;
//Parameterized constructor
public Production(String title, String director, String writer) {
super();
this.title = title;
this.director = director;
this.writer = writer;
}
//Setters and getters.
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
//display() method which displays the Instance variable values
public void display()
{
System.out.println(\"Title: \" + this.title);
System.out.println(\"Director: \" + this.director);
System.out.println(\"Writer: \" + this.writer);
}
//toString() method is used to display the contents of an object
@Override
public String toString() {
return \"Title :\" + title + \"\ Director :\" + director
+ \"\ Writer :\" + writer;
}
}
___________________________________________
Film.java
public class Film extends Production{
//Declaring instance variables
private int boxOfficeGross;
//Parameterized constructor
public Film(String title, String director, String writer, int boxOfficeGross) {
super(title, director, writer);
this.boxOfficeGross = boxOfficeGross;
}
//Setters and getters.
public int getBoxOfficeGross() {
return boxOfficeGross;
}
public void setBoxOfficeGross(int boxOfficeGross) {
this.boxOfficeGross = boxOfficeGross;
}
//display() method which displays the Instance variable values
public void display()
{
System.out.println(\"BoxOfiiceGross: \" + this.boxOfficeGross);
}
//toString() method is used to display the contents of an object
@Override
public String toString() {
return super.toString()+\"\ BoxOfficeGross :\" + boxOfficeGross+\"\ \";
}
}
_______________________________________________
Play.java
public class Play extends Production {
//Declaring instance variables
private int performances;
//Parameterized constructor
public Play(String title, String director, String writer, int performances) {
super(title, director, writer);
this.performances = performances;
}
//Setters and getters.
public int getPerformances() {
return performances;
}
public void setPerformances(int performances) {
this.performances = performances;
}
//display() method which displays the Instance variable values
public void display()
{
System.out.println(\"Performances: \" + this.performances);
}
//toString() method is used to display the contents of an object
@Override
public String toString() {
return super.toString()+\"\ Performances :\" + performances+\"\ \";
}
}
_______________________________________________
Musical.java
public class BobsTerribleTests
{
public static void main(String[] args)
{
//Creating an Film Object by passing parameters
Film titanic = new Film(\"Titanic\", \"James Cameron\", \"James Cameron\.
For the following questions, you will implement the data structure to.pdfarjunhassan8
For the following questions, you will implement the data structure to store information used by a
local car dealer. Each car has some information and stored in a text files called cars: Write a
main program for all questions to let the user enter, delete, search for information, and print
current cars stored in the data structure. Cars formatted so car records separated by a blank line.
Each record contains (in order, each in a single line): Make (manufacturer). Model, Year,
Mileage, Price. Implement a double linked-list to store cars data. Write a double linked-list class
including search, delete, append (to the head and tail), and remove (from the head and tail).
Implement a FIFO queue of car data using the double linked-list. You can use the double linked
list you wrote in Q1. Implement a max-heap of cars data that can extract the car with the highest
price. Write a max-heap class including heapify, build heap, extract, and insertion. Implement a
binary search tree of car data. Write a BST class including search, insertion, and deletion.
Solution
Cars.java
package pacages;
public class Cars {
String make;
String model;
int year;
double mileage;
double price;
// Setters and getters for the Cars member variables
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getMileage() {
return mileage;
}
public void setMileage(double mileage) {
this.mileage = mileage;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString()
{
return \"Make: \"+getMake()+ \" Model: \"+getModel()+ \" Year: \"+getYear() + \"
Mileage: \"+getMileage() + \" Price: \"+getPrice();
}
}
DoublyLinkedList.java
package pacages;
class Node
{
protected Cars data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = null;
}
/* Constructor */
public Node(Cars d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev()
{
return prev;
}
/* Function to set data to node */
public void setData(Cars d)
{
data = d;
}
/* Function to get data from node */
public Cars getData()
{
return data;
}
}
/* Class linkedList */
public class DoublyLinkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public DoublyLinkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of list */
public.
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
Creat Shape classes from scratch DETAILS You will create 3 shape classes (Circle, Rectangle,
Triangle) that all inherit from a single abstract class called AbstractShape which implements
Shape (also created by you). You are also responsible for creating the driver class
\"Assignment7.java\" (program that tests your classes and described on page 3) which does the
following reads input data from a file instantiates various objects of the three shapes based on the
input data stores each in a LinkedList outputs this list to an output file sorts a \"copy\" of this
LinkedList of objects outputs the sorted version of the list to the output file outputs the original
list to the output file This driver program also needs to \"ignore errors in the input file that breach
the specified input format as described in the Assianment7,java details (see page 3 1. Shape.java
This is an interface that has 2 abstract methods, and passes the responsibility of implementing the
compareTo method to the class that implements Shape (you may note, nomally Comparable is
\"implemented\" by a class. However, an interface cannot implement because interfaces can only
contain abstract methods. That said, an interface can only extend other interfaces and the
responsibility of actually \"implementing\" the abstract method(s) of the super class interface is
passed on to the sub-classes) public interface Shape extends Comparable public double
calculateAreal) Il This abstract method is implemented at the concrete level public Shape
copyShape); Il also implemented at the concrete level 2. AbstractShape.java public abstract class
AbstractShape implements Shape This class should contain an instance field to store the name of
each obiect. The constructor which sets this field should receive the name and a number to be
concatenated to the name and then stored in the name field Recall, when the super class has a
parameterized constructor, the sub-classes will need to call it AND the sub- classes will need to
also provide a constructor without parameters This abstract class will implement the compareTo
method passed on from the Shape interface and will pass on the responsibility of implementing
calculateArea to the extending sub-classes (compare To will use the calculateArea method when
comparing 2 Shape objects). Along with compare To, one more concrete method should be
included. The following will be used by the sub-classes\' toString method: public String
getName) II Simply returns the name field data
Solution
in7.txt
4.4
2.5 3
8.1 3.0 5.0
2.5 3 4
2.5
tuesday
-7
1.0
3 three
3 -9
3 5
1.0
Assignment7.java
import java.io.*;
import java.util.*;
public class Assignment7 {
/**
* This is the test driver class that will include main.
* This program MUST read a file named in7.txt and
* generate an output file named out7.txt. The in7.txt
* file must be created by you based on formatting
* described shortly.
*
* @param theArgs
*/
public static void main(String[] theArgs) {
List myList = new Arra.
operating system linux,ubuntu,Mac Geometri.pdfaquadreammail
//operating system linux,ubuntu,Mac
/*********************GeometricObject.java**********************/
public abstract class GeometricObject {
private String color = \"white\";
private boolean filled;
// default constructure
public GeometricObject() {
super();
// TODO Auto-generated constructor stub
}
// construct a Geometric Object
// parameterized constructure
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
/** Getter method for color */
public String getColor() {
return color;
}
/** Setter method for color */
public void setColor(String color) {
this.color = color;
}
/**
* Getter method for filled. Since filled is boolean, so the gret method
* name is isFilled
*/
public boolean isFilled() {
return filled;
}
/** Setter method for filled */
public void setFilled(boolean filled) {
this.filled = filled;
}
/** Abstract method for FindArea */
public abstract double findArea();
/** Abstract method for findPerimeter */
public abstract double findPerimeter();
}
/*****************************Octagon.java**************/
public class Octagon extends GeometricObject implements Cloneable, Comparable {
private double side;
/** construct a Octagon with specified side */
public Octagon(double side) {
super();
this.side = side;
}
/** Implement the abstract method findArea in GeometricObject */
@Override
public double findArea() {
double area = (2 + 4 / Math.sqrt(2)) * side * side;
return area;
}
/** Implement the abstract method findArea in findPerimeter */
@Override
public double findPerimeter() {
double perimeter = 8 * side;
return perimeter;
}
/** Implement the compareTo method in Comparable interface */
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/*******************App.java*******************/
public class App {
public static void main(String[] args) {
Octagon a1 = new Octagon(5);//creating object of octagon
System.out.println(\"Area of a1 is \" + a1.findArea());
System.out.println(\"Perimeter of a1 is \" + a1.findPerimeter());
Object a2;
try {
a2 = a1.clone();
String result = (a1.compareTo(a2) == 0) ? \"a1 and its clone a2 have the same area\"
: \"a1 and its clone a2 have different areas\";
System.out.println(\"Compare a1 and its clone a2:\ \\t \" + result);
System.out.println(\"Hashcode of a1: \" + a1.hashCode());
System.out.println(\"Hashcode of a2: \" + a2.hashCode());
System.out.println(\"Displaying a1: \" + a1);
System.out.println(\"Displaying a2: \" + a2);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
/*****************output***************/
gopal@gopal:~/Desktop/chegg$ javac GeometricObject.java
gopal@gopal:~/Desktop/chegg$ javac Octagon.java
gopal@gopal:~/Desktop/chegg$ javac App.java
gopal@gopal:~/Desktop/chegg$ java App
Area of a1 is 120.71067811865476
Perimeter of a1 is 40.0
Compare a1 and its clone a2:
a1 and its clone a2 have the same area
.
Pragmatic functional refactoring with java 8 (1)RichardWarburton
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
* How to adapt to requirement changes using first-class functions
* How you can enhance code reusability using currying
* How you can make your code more robust by favouring immutability over mutability
* How you can design better APIs and reduce unintended null pointer exceptions using an optional data type
Los olores del código (Code Smells en inglés) son la forma que utilizamos para referirnos a signos en el código fuente que podrían indicar un problema más profundo.
Un code smell no tiene por qué implicar que una aplicación no funcione correctamente. Indica un problema de diseño que puede enlentecer el desarrollo, generar más errores en el futuro y hacer aparecer una mayor cantidad de bugs en nuestra aplicación. Dentro de las buenas prácticas de programación, con el objetivo de escribir cada vez mejor código, necesitamos ir aprendiendo todos estos signos.
Code to copy:
/******************** Person.java **********************/
// Create a class Person
publicclass Person
{
// Declare variables
private String name;
private MyDate birthdate; // This is a date based on a Person\'s birthday
// Create accessor method for the name
public String getName()
{
return name;
}
// Create mutator method for name
publicvoid setName(String name)
{
this.name = name;
}
// Create accessor method for the name
public MyDate getBirthdate()
{
return birthdate;
}
// Create mutator method for name
publicvoid setBirthdate(MyDate birthdate)
{
this.birthdate = birthdate;
}
// Create a parameter constructor
public Person(String name, int pp, int kk, int vv)
{
this(name, new MyDate(pp, kk, vv));
}
// Create a parameter constructor
public Person(String name, MyDate birthday)
{
this(name);
this.birthdate = birthday;
}
// Create a parameter constructor
public Person(String name) {
this.name = name;
}
// Create to string method to display person data
@Override
public String toString() {
return \"Person [name=\" + name + \", birthdate=\" + birthdate + \"]\";
}
}
/******************** MyDate.java **********************/
// Create a class named MyDate
class MyDate
{
// Declare variables
privateint day;
privateint month;
privateint year;
// Create a default constructor
public MyDate(int month, int day, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
// Create a compareTo method to compare the date objects
int compareTo(MyDate obj)
{
if(obj.day==this.day && obj.month==this.month && obj.year==this.year)
{
return 0;
}
elseif(obj.year>this.year)
{
return 1;
}
elseif(obj.year > this.year && obj.month > this.month)
{
return 1;
}
elseif(obj.year > this.year && obj.month > this.month && obj.day==this.day)
{
return 1;
}
else
return -1;
}
// Create a toString() method to display the date
@Override
public String toString()
{
return \"MyDate [day=\" + day + \", month=\" + month + \", year=\" + year + \"]\";
}
}
/******************** PersonSort.java **********************/
// import statements
import java.util.*;
import java.io.*;
// Create a class PersonSort
publicclass PersonSort implements Comparator
{
// Create compare method to compare two objects
@Override
publicint compare(Person o1, Person o2)
{
return 0;
}
// Create a main method to test the program
publicstaticvoid main(String [] args)
{
// Declare variables
String line;
String fileName=\"dataFile.txt\";
String data=\"\";
// Create a array list for the person class
ArrayList person= new ArrayList();
// Create a try block to handle the run time exceptions
try
{
// Create an object for the FileReader class
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// Create a for loop to read the data in the file dataFile.txt
while ((line = bufferedReader.readLine()) != null)
{
data+=line;
}
}
// Create a catch block to catch run time exceptions.
catch (FileNotFoundException ex)
{
System.out.println(\"Unable to op.
import java-util-ArrayList- public class Bus { private String na.pdfGordonF2XPatersonh
import java.util.ArrayList;
public class Bus {
private String name;
private int size;
private int basePrice;
private ArrayList<Trip> approvedTrips;
private int level; // 1,2,3 for low,medium, high repectively;
private int id;
private static int nextId=0;
private Ministry mny;
protected String tripTypes;
private int getNextId(){
return nextId++;
}
public Bus(){
approvedTrips=new ArrayList<Trip>();
}
public Bus( String name, int size, int basePrice, int lev, Ministry mny) {
approvedTrips=new ArrayList<Trip>();
this.name = name;
this.size =size;
this.basePrice = basePrice;
this.level = lev;
this.id = getNextId();
this.mny = mny;
tripTypes = "BASICTRANSPORT";
}
public boolean available(Date date){
boolean retval = true;
for (Trip t:approvedTrips)
if (t.getDate().getDay() == date.getDay())
retval = false;
return retval;
}
public int getBasePrice(){
return basePrice;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public double getSize(){
return size;
}
public String toString(){
return name;
}
public boolean isSuitable(String type){
return tripTypes.contains(type);
}
public int getEstimate(String type, int numPassengers, int comfortLevel){
return basePrice;
}
public boolean canHold(int numPassengers, int comfortLevel){
int capacity = (int)(size / mny.getSeparation(comfortLevel));
return numPassengers <=capacity;
}
public void promoteTrips(){
System.out.println();
System.out.println("TRIPS ON " +getName());
System.out.println("===================");
for (Trip t:approvedTrips)
System.out.println(t);
}
public int reserve(Trip trip, Ministry mny){
int retval = -1;
ApprovalRequest ar = new ApprovalRequest(trip, this);
int result = mny.checkApproval(ar);
if (result >=0){
int est = getEstimate(trip.getType(), trip.getNumPeople(), trip.getComfortLevel());
if (trip.getPlanner().getBudget() >= getEstimate(trip.getType(), trip.getNumPeople(),
trip.getComfortLevel())){
approvedTrips.add(trip);
trip.setBus(this);
retval = result;
}
}
return retval;
}
Complete the following code based on these instructions :
COMPLETING THE PLANNER class The int planTrip(int numPassengers, String tripType,
Date date, int comfortLevel) method of Planner plans an trip of a given type with the specified
number of passengers on the specified date. Steps include: a. Determine the set of buses that the
promoter can afford b. Find the lowest cost Bus from the set of affordable buses that i. can hold
the number of passengers and ii. is available c. If there is at least one Bus that meets the
requirements i. Create an instance of a Trip ii. Call the reserve method of the Bus and capture the
return value in an integer iii. If the return value is greater than or equal to 0, 1. Call the setBus
method of the trip to the selected bus 2. Pay for the selected bus 3. Return the return value as the
result of planTrip d. If plans for the trip did not work out, return -1
import java.util.ArrayList;
public class Planner
{
private String name;
private double budget;
private .
import java.util.Random;
//ASSIGNMENT #2: MATRIX ARITHMETIC
//Class Matrix. File: Matrix.java
public class Matrix {
public static final int MAX = 20;
//Attributes
private int size;
private int[][] table;
/**
* Default constructor
* Initializes the table with size MAX
*/
public Matrix() {
this.table = new int[MAX][MAX];
}
/**
* Parameterized constructor
* Initializes the table with size s
*/
public Matrix(int s) {
this.size = s;
this.table = new int[this.size][this.size];
}
/**
* Returns the size of the matrix
* @return
*/
public int getSize() {
return this.size;
}
/**
* The the number at position (r, c)
* @param r
* @param c
* @return
*/
public int getElement(int r, int c) {
return this.table[r][c];
}
/**
* Set a number at position (r, c)
* @param r
* @param c
* @param value
*/
public void setElement(int r, int c, int value) {
this.table[r][c] = value;
}
/**
* Initializes the matrix with random numbers
* @param low
* @param up
*/
public void init(int low, int up) {
Random rand = new Random();
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
setElement(r, c, rand.nextInt(up) + low);
}
}
}
/**
* Prints the matrix
*/
public void print() {
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
System.out.printf(\" %2s\", getElement(r, c));
}
System.out.printf(\"\ \");
}
}
/**
* Adds this matrix with Matrix a
* @param a
* @return
*/
public Matrix add(Matrix a) {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
int value = this.getElement(r, c) + a.getElement(r, c);
result.setElement(r, c, value);
}
}
return result;
}
/**
* Subtracts this matrix with Matrix a
* @param a
* @return
*/
public Matrix subtract(Matrix a) {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
int value = this.getElement(r, c) - a.getElement(r, c);
result.setElement(r, c, value);
}
}
return result;
}
/**
* Multiplies this matrix with Matrix a
* @param a
* @return
*/
public Matrix multiply(Matrix a) {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
int value = 0;
for (int k = 0 ; k < this.size ; k++) {
value += this.getElement(r, k) * a.getElement(k, c);
}
result.setElement(r, c, value);
}
}
return result;
}
/**
* Multiplies this matrix with a constant whatConst
* @param a
* @return
*/
public Matrix multiplyConst(int whatConst) {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
result.setElement(r, c, getElement(r, c) * whatConst);
}
}
return result;
}
/**
* Transposes this matrix
* @param a
* @return
*/
public Matrix transpose() {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
result.setElement(r, c, this.getElement(c, r));
}
}
return result;
}
/**
*
* @param a
* @return
*/
p.
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docxhoney725342
1
MVC – Ajax and Modal Views
AJAX stands for Asynchronous JavaScript and XML. It is a client-side capability that allows
silent updates of parts of a web page. Every browser provides a component called
XmlHttpRequest that is invoked via Javascript and has the capability to make asynchronous calls
back to the web server from where the page was obtained. One can set up Javascript timers to
automate the periodic retrieval of data using the XmlHttpRequest object.
Even though we can program the XmlHttpRequest object directly using Javascript, JQuery
makes it a lot easier to set it up and issue an asynchronous request to the web server. ASP.Net
MVC also provides a server-side solution to AJAX via the Ajax.BeginForm extension method.
We will demonstrate the two approaches to AJAX i.e., via JQuery and serializable partial views,
and via the Ajax.BeginForm.
Using SQL Server Management Studo, create a database called ProductsDB. Add a table called
Categories with the folling data.
The CategoryId column is of type int, and the CategoryName column is of type carchar(50).
Add another table called Products with the following design.
Then put the following data in the Products table.
2
Using Visual Studio, create a new project. Choose the web type of project, and select the MVC
template as shown below.
Add the following connection string information to the web.config file. Replace ALPHA with
the name of your database server.
<configuration>
<connectionStrings>
<add name="PRODUCTSDB" connectionString="server=ALPHA;integrated
security=true;database=ProductsDB" />
</connectionStrings>
<appSettings>
Add a class to the Models folder called Category with the following code in it.
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
3
Add a folder called DataLayer to the project. Then add an interface called IEntity to it with the
following code in it.
public interface IEntity
{ // any class that needs conversion to a List from a DataTable will implement this
void PopulateFields(DataRow dr);
}
Add a class called MyEntityBase to the Models folder with the following code in it. This class
uses reflection to populate the fields of a class from a given DataRow of a DataTable. All
repository methods that need to convert a DataTable to a list will indirectly use this method via
the generic DBList class..
public class MyEntityBase : IEntity
{
public void PopulateFields(DataRow dr)
{
// use reflection to populate the fields of this class from DataRow
Type tp = this.GetType();
foreach (PropertyInfo pi in tp.GetProperties())
pi.SetValue(this, dr[pi.Name]);
}
}
Add a class called DBList to the DataLayer folder with the following code in it.
class DBList
{
...
Simple array Java code.The “Park-a-lot” parking garage currently o.pdffasttracktreding
Simple array Java code.
The “Park-a-lot” parking garage currently operates without any computerized system. The
management has concerns about inefficiencies of sub-optimal usage of parking space (lost
opportunity/profit). Congestion inside the garage is often caused by drivers searching for vacant
spots. Currently, the management monitors the garage occupancy by having employees walk
around the decks to inspect the occupancy of individual spots.
Now you are hired to develop a more advanced system to track and manage occupancy of a
parking garage and allow customers to find and reserve available parking places.
1. There are 50 parking spaces in total in this parking lot garage
2. The occupancy state of each parking spot: “available,” “reserved,” or “occupied”
3. The customer should be able to check the parking space availability by specifying the desired
date and time interval. If the system responds stating that there are available spots, the customer
should be able to make the parking reservation by data and time
4. The customer should be able to modify their existing reservation(s) before the start time of
their particular reservation.
5. The customer should be able to extend their current occupancy of a parking space only before
their current ending time
Solution
// importing all required libraries
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
/*
The CarFrame class is an implementation of the JFrame and
also contains the main method. Usage:
> java CarFrame
Note that the file carData.txt must be in the same directory as
all compiled code.
*/
public class CarFrame extends JFrame
{
public static JTabbedPane index;
public static CarLot myCarLot;
public CarFrame()
{
// setting window properties
this.setSize(Toolkit.getDefaultToolkit().getScreenSize());
this.setDefaultCloseOperation(3);
this.setTitle(\"Car Park System\");
this.setResizable(false);
Color newColor = new Color(0.2f, 0.1f, 0.8f, 0.1f);
// creating Car Lot object
myCarLot = new CarLot(15, \"carData.txt\");
// building tabbed panel display
index = new JTabbedPane();
index.setBackground(newColor);
final JPanel statusTab = Status.startup();
final JPanel addOrRemoveCarTab = AddOrRemoveCar.startup();
// adding tabs to tabbed panel
index.addTab(\"Lot Status\", statusTab);
index.addTab(\"Add Or Remove Cars\", addOrRemoveCarTab);
// setting content pane
this.getContentPane().add(index);
}
public static void main(String[] args)
{
// initialize frame and set visible
CarFrame main = new CarFrame();
main.setVisible(true);
}
}
class CarLot
{
// class variables
private Vector registeredDrivers;
private Vector parkingStalls;
private String dataFile;
private int maxLotSize;
// constructor
public CarLot(int maxSize, String fileName)
{
registeredDrivers = new Vector();
parkingStalls = new Vector();
maxLotSize = maxSize;
dataFile = fileName;
loadData();
}
public String getDataFileName()
{
return dataFile;
}
public int.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Demo {
static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
ListnameList=createListOfNames();
try {
// Declare variable for user\'s option
int menuOption = 0;
do {
// Setting menuOption equal to return value from showMenu() function;
menuOption = showMenu();
// switch case as per the user option
switch (menuOption) {
case 1:
int correctAnswer=hardProblem(nameList);
System.out.println(\"Correct Answer :\"+correctAnswer);
break;
case 2:
int correctAnswerEasy=easyProblem(nameList);
System.out.println(\"Correct Answer :\"+correctAnswerEasy);
break;
case 3:
System.out.println(\"Quitting Program..\");
break;
default:
System.out.println(\"Sorry, Please enter valid Option\");
}// End of switch statement
} while (menuOption != 3);
} catch (Exception ex) {
// Error Message
System.out.println(\"Sorry problem occured within Program\");
// flushing scanner
scanner.next();
} finally {
// Ensuring that scanner will always be closed and cleaning up
// resources
scanner.close();
}
}// End of main Method
/**
* Method that prints menu to screen and gets returns user\'s option from menu
* @return Returns user Option
*/
public static int showMenu() {
// Declaring var for user option and defaulting to 0
int option = 0;
// Printing menu to screen
System.out.println(\"Menu:\");
System.out.println(\"1.Hard Problem\");
System.out.println(\"2.Easy Problem\");
System.out.println(\"3. Quit\");
// Getting user option from above menu
System.out.println(\"Enter Option from above...\");
option = scanner.nextInt();
return option;
}
public static ListcreateListOfNames(){
ListnameList=new ArrayList();
System.out.println(\"Enter the number of children to enter\");
int num=scanner.nextInt();
for(int i=0;inameList){
int correctAnswers=0;
int day=0;
for(String name:nameList){
boolean correct=false;
int index=day%nameList.size();
String childForDishDuty=nameList.get(index);
System.out.println(\"Please enter the child name\");
String userInput=scanner.next();
if(childForDishDuty.equalsIgnoreCase(userInput)){
correct=true;
}
if(correct){
correctAnswers++;
}
day++;
}
return correctAnswers;
}
public static int easyProblem(ListnameList){
int correctAnswers=0;
int day=0;
for(String name:nameList){
boolean correct=false;
int index=day%nameList.size();
String childForDishDuty=\"Day \"+day+\":\"+nameList.get(index)+\" must do the
dishes\";
System.out.println(childForDishDuty);
System.out.println(\"Please enter the child name\");
String userInput=scanner.next();
if(nameList.get(index).equalsIgnoreCase(userInput)){
correct=true;
}
if(correct){
correctAnswers++;
}
day++;
}
return correctAnswers;
}
}
Solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Demo {
static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
ListnameList=createListOfNames();
try {
// Declare variable for user\'s option
int .
In 2008 Android app code had a lot of boilerplate, and was very error prone.
More code.. more bugs!
Now it doesn't have to be... but that is an option that each developer needs to take!
Java programI made this Account.java below. Using the attached cod.pdffathimafancy
Java program
I made this Account.java below. Using the attached code I need help with 10.7 (Game: ATM
machine)
Use the Account class created in Programming Exercise 9.7 to simulate an ATM machine.
Create ten accounts in an array with id 0, 1, . . . , 9, and initial balance $100.
The system prompts the user to enter an id. If the id is entered incorrectly, ask the user to enter a
correct id.
Once an id is accepted, the main menu is displayed as shown in the sample run.
You can enter a choice 1 for viewing the current balance, 2 for withdrawing money, 3 for
depositing money, and 4 for exiting the main menu.
Once you exit, the system will prompt for an id again. Thus, once the system starts, it will not
stop.
*/
import java.util.Date;
public class Account {
/**
* @param args
*/
private int id=0;
private double balance=0;
private double annualIntrestRate=0;
private Date dateCreated;
public Account() {
super();
}
public Account(int id, double balance) {
super();
this.id = id;
this.balance = balance;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualIntrestRate() {
return annualIntrestRate;
}
public void setAnnualIntrestRate(double annualIntrestRate) {
this.annualIntrestRate = annualIntrestRate;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public double getMonthlyInterestRate()
{
return (this.getAnnualIntrestRate()/12);
}
public double getMonthlyInterest()
{
return (getBalance() *getMonthlyInterestRate()/100);
}
public double withDraw(double balance)
{
this.setBalance(this.getBalance()-balance);
return this.getBalance();
}
public double diposite(double balance)
{
this.setBalance(this.getBalance()+balance);
return this.getBalance();
}
public double totalBalance()
{
balance =balance + getMonthlyInterest();
return balance;
}
}
//AccountTest.java
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class AccountTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
Account ac=new Account(1,5000.00);
System.out.println(\"Enter the annual intrest rate\");
double intrestRate=sc.nextDouble();
ac.setAnnualIntrestRate(intrestRate);
Date d=new Date();
Calendar currentDate = Calendar.getInstance();
ac.setDateCreated(currentDate.getTime());
System.out.println(\"Date id \"+ac.getDateCreated());
System.out.println(\"Monthly intrest rate is :\"+ac.getMonthlyInterestRate());
System.out.println(\"Monthly intrest is :\"+ac.getMonthlyInterest());
System.out.println(\"Enter Amount for diposite \");
double dipositeAmount=sc.nextDouble();
System.out.println(\"The amount after diposite is :\"+ac.diposite(dipositeAmount));
System.out.println(\"Enter Amount to withdraw :\");
double withdramount= sc.nextDouble.
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
pH = pKa + log (Sa) where S =moles of salt a = m.pdfanujsharmaanuj14
pH = pKa + log (S/a) where S =moles of salt a = moles of acid pH = 4.745 + log
(0.025 / 0.1) = 4.143
Solution
pH = pKa + log (S/a) where S =moles of salt a = moles of acid pH = 4.745 + log
(0.025 / 0.1) = 4.143.
H is reduced, while Fe is oxidized. Note the oxi.pdfanujsharmaanuj14
H is reduced, while Fe is oxidized. Note: the oxidation state of H changes from +1
In HI to 0 in H2. the oxidation state of Fe changes from 0 in Fe(CO)5 to +2 in Fe(CO)4I2. CO is
a neutral ligand.
Solution
H is reduced, while Fe is oxidized. Note: the oxidation state of H changes from +1
In HI to 0 in H2. the oxidation state of Fe changes from 0 in Fe(CO)5 to +2 in Fe(CO)4I2. CO is
a neutral ligand..
Pragmatic functional refactoring with java 8 (1)RichardWarburton
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
* How to adapt to requirement changes using first-class functions
* How you can enhance code reusability using currying
* How you can make your code more robust by favouring immutability over mutability
* How you can design better APIs and reduce unintended null pointer exceptions using an optional data type
Los olores del código (Code Smells en inglés) son la forma que utilizamos para referirnos a signos en el código fuente que podrían indicar un problema más profundo.
Un code smell no tiene por qué implicar que una aplicación no funcione correctamente. Indica un problema de diseño que puede enlentecer el desarrollo, generar más errores en el futuro y hacer aparecer una mayor cantidad de bugs en nuestra aplicación. Dentro de las buenas prácticas de programación, con el objetivo de escribir cada vez mejor código, necesitamos ir aprendiendo todos estos signos.
Code to copy:
/******************** Person.java **********************/
// Create a class Person
publicclass Person
{
// Declare variables
private String name;
private MyDate birthdate; // This is a date based on a Person\'s birthday
// Create accessor method for the name
public String getName()
{
return name;
}
// Create mutator method for name
publicvoid setName(String name)
{
this.name = name;
}
// Create accessor method for the name
public MyDate getBirthdate()
{
return birthdate;
}
// Create mutator method for name
publicvoid setBirthdate(MyDate birthdate)
{
this.birthdate = birthdate;
}
// Create a parameter constructor
public Person(String name, int pp, int kk, int vv)
{
this(name, new MyDate(pp, kk, vv));
}
// Create a parameter constructor
public Person(String name, MyDate birthday)
{
this(name);
this.birthdate = birthday;
}
// Create a parameter constructor
public Person(String name) {
this.name = name;
}
// Create to string method to display person data
@Override
public String toString() {
return \"Person [name=\" + name + \", birthdate=\" + birthdate + \"]\";
}
}
/******************** MyDate.java **********************/
// Create a class named MyDate
class MyDate
{
// Declare variables
privateint day;
privateint month;
privateint year;
// Create a default constructor
public MyDate(int month, int day, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
// Create a compareTo method to compare the date objects
int compareTo(MyDate obj)
{
if(obj.day==this.day && obj.month==this.month && obj.year==this.year)
{
return 0;
}
elseif(obj.year>this.year)
{
return 1;
}
elseif(obj.year > this.year && obj.month > this.month)
{
return 1;
}
elseif(obj.year > this.year && obj.month > this.month && obj.day==this.day)
{
return 1;
}
else
return -1;
}
// Create a toString() method to display the date
@Override
public String toString()
{
return \"MyDate [day=\" + day + \", month=\" + month + \", year=\" + year + \"]\";
}
}
/******************** PersonSort.java **********************/
// import statements
import java.util.*;
import java.io.*;
// Create a class PersonSort
publicclass PersonSort implements Comparator
{
// Create compare method to compare two objects
@Override
publicint compare(Person o1, Person o2)
{
return 0;
}
// Create a main method to test the program
publicstaticvoid main(String [] args)
{
// Declare variables
String line;
String fileName=\"dataFile.txt\";
String data=\"\";
// Create a array list for the person class
ArrayList person= new ArrayList();
// Create a try block to handle the run time exceptions
try
{
// Create an object for the FileReader class
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// Create a for loop to read the data in the file dataFile.txt
while ((line = bufferedReader.readLine()) != null)
{
data+=line;
}
}
// Create a catch block to catch run time exceptions.
catch (FileNotFoundException ex)
{
System.out.println(\"Unable to op.
import java-util-ArrayList- public class Bus { private String na.pdfGordonF2XPatersonh
import java.util.ArrayList;
public class Bus {
private String name;
private int size;
private int basePrice;
private ArrayList<Trip> approvedTrips;
private int level; // 1,2,3 for low,medium, high repectively;
private int id;
private static int nextId=0;
private Ministry mny;
protected String tripTypes;
private int getNextId(){
return nextId++;
}
public Bus(){
approvedTrips=new ArrayList<Trip>();
}
public Bus( String name, int size, int basePrice, int lev, Ministry mny) {
approvedTrips=new ArrayList<Trip>();
this.name = name;
this.size =size;
this.basePrice = basePrice;
this.level = lev;
this.id = getNextId();
this.mny = mny;
tripTypes = "BASICTRANSPORT";
}
public boolean available(Date date){
boolean retval = true;
for (Trip t:approvedTrips)
if (t.getDate().getDay() == date.getDay())
retval = false;
return retval;
}
public int getBasePrice(){
return basePrice;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public double getSize(){
return size;
}
public String toString(){
return name;
}
public boolean isSuitable(String type){
return tripTypes.contains(type);
}
public int getEstimate(String type, int numPassengers, int comfortLevel){
return basePrice;
}
public boolean canHold(int numPassengers, int comfortLevel){
int capacity = (int)(size / mny.getSeparation(comfortLevel));
return numPassengers <=capacity;
}
public void promoteTrips(){
System.out.println();
System.out.println("TRIPS ON " +getName());
System.out.println("===================");
for (Trip t:approvedTrips)
System.out.println(t);
}
public int reserve(Trip trip, Ministry mny){
int retval = -1;
ApprovalRequest ar = new ApprovalRequest(trip, this);
int result = mny.checkApproval(ar);
if (result >=0){
int est = getEstimate(trip.getType(), trip.getNumPeople(), trip.getComfortLevel());
if (trip.getPlanner().getBudget() >= getEstimate(trip.getType(), trip.getNumPeople(),
trip.getComfortLevel())){
approvedTrips.add(trip);
trip.setBus(this);
retval = result;
}
}
return retval;
}
Complete the following code based on these instructions :
COMPLETING THE PLANNER class The int planTrip(int numPassengers, String tripType,
Date date, int comfortLevel) method of Planner plans an trip of a given type with the specified
number of passengers on the specified date. Steps include: a. Determine the set of buses that the
promoter can afford b. Find the lowest cost Bus from the set of affordable buses that i. can hold
the number of passengers and ii. is available c. If there is at least one Bus that meets the
requirements i. Create an instance of a Trip ii. Call the reserve method of the Bus and capture the
return value in an integer iii. If the return value is greater than or equal to 0, 1. Call the setBus
method of the trip to the selected bus 2. Pay for the selected bus 3. Return the return value as the
result of planTrip d. If plans for the trip did not work out, return -1
import java.util.ArrayList;
public class Planner
{
private String name;
private double budget;
private .
import java.util.Random;
//ASSIGNMENT #2: MATRIX ARITHMETIC
//Class Matrix. File: Matrix.java
public class Matrix {
public static final int MAX = 20;
//Attributes
private int size;
private int[][] table;
/**
* Default constructor
* Initializes the table with size MAX
*/
public Matrix() {
this.table = new int[MAX][MAX];
}
/**
* Parameterized constructor
* Initializes the table with size s
*/
public Matrix(int s) {
this.size = s;
this.table = new int[this.size][this.size];
}
/**
* Returns the size of the matrix
* @return
*/
public int getSize() {
return this.size;
}
/**
* The the number at position (r, c)
* @param r
* @param c
* @return
*/
public int getElement(int r, int c) {
return this.table[r][c];
}
/**
* Set a number at position (r, c)
* @param r
* @param c
* @param value
*/
public void setElement(int r, int c, int value) {
this.table[r][c] = value;
}
/**
* Initializes the matrix with random numbers
* @param low
* @param up
*/
public void init(int low, int up) {
Random rand = new Random();
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
setElement(r, c, rand.nextInt(up) + low);
}
}
}
/**
* Prints the matrix
*/
public void print() {
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
System.out.printf(\" %2s\", getElement(r, c));
}
System.out.printf(\"\ \");
}
}
/**
* Adds this matrix with Matrix a
* @param a
* @return
*/
public Matrix add(Matrix a) {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
int value = this.getElement(r, c) + a.getElement(r, c);
result.setElement(r, c, value);
}
}
return result;
}
/**
* Subtracts this matrix with Matrix a
* @param a
* @return
*/
public Matrix subtract(Matrix a) {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
int value = this.getElement(r, c) - a.getElement(r, c);
result.setElement(r, c, value);
}
}
return result;
}
/**
* Multiplies this matrix with Matrix a
* @param a
* @return
*/
public Matrix multiply(Matrix a) {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
int value = 0;
for (int k = 0 ; k < this.size ; k++) {
value += this.getElement(r, k) * a.getElement(k, c);
}
result.setElement(r, c, value);
}
}
return result;
}
/**
* Multiplies this matrix with a constant whatConst
* @param a
* @return
*/
public Matrix multiplyConst(int whatConst) {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
result.setElement(r, c, getElement(r, c) * whatConst);
}
}
return result;
}
/**
* Transposes this matrix
* @param a
* @return
*/
public Matrix transpose() {
Matrix result = new Matrix(this.size);
for (int r = 0 ; r < this.size ; r++) {
for (int c = 0 ; c < this.size ; c++) {
result.setElement(r, c, this.getElement(c, r));
}
}
return result;
}
/**
*
* @param a
* @return
*/
p.
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docxhoney725342
1
MVC – Ajax and Modal Views
AJAX stands for Asynchronous JavaScript and XML. It is a client-side capability that allows
silent updates of parts of a web page. Every browser provides a component called
XmlHttpRequest that is invoked via Javascript and has the capability to make asynchronous calls
back to the web server from where the page was obtained. One can set up Javascript timers to
automate the periodic retrieval of data using the XmlHttpRequest object.
Even though we can program the XmlHttpRequest object directly using Javascript, JQuery
makes it a lot easier to set it up and issue an asynchronous request to the web server. ASP.Net
MVC also provides a server-side solution to AJAX via the Ajax.BeginForm extension method.
We will demonstrate the two approaches to AJAX i.e., via JQuery and serializable partial views,
and via the Ajax.BeginForm.
Using SQL Server Management Studo, create a database called ProductsDB. Add a table called
Categories with the folling data.
The CategoryId column is of type int, and the CategoryName column is of type carchar(50).
Add another table called Products with the following design.
Then put the following data in the Products table.
2
Using Visual Studio, create a new project. Choose the web type of project, and select the MVC
template as shown below.
Add the following connection string information to the web.config file. Replace ALPHA with
the name of your database server.
<configuration>
<connectionStrings>
<add name="PRODUCTSDB" connectionString="server=ALPHA;integrated
security=true;database=ProductsDB" />
</connectionStrings>
<appSettings>
Add a class to the Models folder called Category with the following code in it.
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
3
Add a folder called DataLayer to the project. Then add an interface called IEntity to it with the
following code in it.
public interface IEntity
{ // any class that needs conversion to a List from a DataTable will implement this
void PopulateFields(DataRow dr);
}
Add a class called MyEntityBase to the Models folder with the following code in it. This class
uses reflection to populate the fields of a class from a given DataRow of a DataTable. All
repository methods that need to convert a DataTable to a list will indirectly use this method via
the generic DBList class..
public class MyEntityBase : IEntity
{
public void PopulateFields(DataRow dr)
{
// use reflection to populate the fields of this class from DataRow
Type tp = this.GetType();
foreach (PropertyInfo pi in tp.GetProperties())
pi.SetValue(this, dr[pi.Name]);
}
}
Add a class called DBList to the DataLayer folder with the following code in it.
class DBList
{
...
Simple array Java code.The “Park-a-lot” parking garage currently o.pdffasttracktreding
Simple array Java code.
The “Park-a-lot” parking garage currently operates without any computerized system. The
management has concerns about inefficiencies of sub-optimal usage of parking space (lost
opportunity/profit). Congestion inside the garage is often caused by drivers searching for vacant
spots. Currently, the management monitors the garage occupancy by having employees walk
around the decks to inspect the occupancy of individual spots.
Now you are hired to develop a more advanced system to track and manage occupancy of a
parking garage and allow customers to find and reserve available parking places.
1. There are 50 parking spaces in total in this parking lot garage
2. The occupancy state of each parking spot: “available,” “reserved,” or “occupied”
3. The customer should be able to check the parking space availability by specifying the desired
date and time interval. If the system responds stating that there are available spots, the customer
should be able to make the parking reservation by data and time
4. The customer should be able to modify their existing reservation(s) before the start time of
their particular reservation.
5. The customer should be able to extend their current occupancy of a parking space only before
their current ending time
Solution
// importing all required libraries
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
/*
The CarFrame class is an implementation of the JFrame and
also contains the main method. Usage:
> java CarFrame
Note that the file carData.txt must be in the same directory as
all compiled code.
*/
public class CarFrame extends JFrame
{
public static JTabbedPane index;
public static CarLot myCarLot;
public CarFrame()
{
// setting window properties
this.setSize(Toolkit.getDefaultToolkit().getScreenSize());
this.setDefaultCloseOperation(3);
this.setTitle(\"Car Park System\");
this.setResizable(false);
Color newColor = new Color(0.2f, 0.1f, 0.8f, 0.1f);
// creating Car Lot object
myCarLot = new CarLot(15, \"carData.txt\");
// building tabbed panel display
index = new JTabbedPane();
index.setBackground(newColor);
final JPanel statusTab = Status.startup();
final JPanel addOrRemoveCarTab = AddOrRemoveCar.startup();
// adding tabs to tabbed panel
index.addTab(\"Lot Status\", statusTab);
index.addTab(\"Add Or Remove Cars\", addOrRemoveCarTab);
// setting content pane
this.getContentPane().add(index);
}
public static void main(String[] args)
{
// initialize frame and set visible
CarFrame main = new CarFrame();
main.setVisible(true);
}
}
class CarLot
{
// class variables
private Vector registeredDrivers;
private Vector parkingStalls;
private String dataFile;
private int maxLotSize;
// constructor
public CarLot(int maxSize, String fileName)
{
registeredDrivers = new Vector();
parkingStalls = new Vector();
maxLotSize = maxSize;
dataFile = fileName;
loadData();
}
public String getDataFileName()
{
return dataFile;
}
public int.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Demo {
static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
ListnameList=createListOfNames();
try {
// Declare variable for user\'s option
int menuOption = 0;
do {
// Setting menuOption equal to return value from showMenu() function;
menuOption = showMenu();
// switch case as per the user option
switch (menuOption) {
case 1:
int correctAnswer=hardProblem(nameList);
System.out.println(\"Correct Answer :\"+correctAnswer);
break;
case 2:
int correctAnswerEasy=easyProblem(nameList);
System.out.println(\"Correct Answer :\"+correctAnswerEasy);
break;
case 3:
System.out.println(\"Quitting Program..\");
break;
default:
System.out.println(\"Sorry, Please enter valid Option\");
}// End of switch statement
} while (menuOption != 3);
} catch (Exception ex) {
// Error Message
System.out.println(\"Sorry problem occured within Program\");
// flushing scanner
scanner.next();
} finally {
// Ensuring that scanner will always be closed and cleaning up
// resources
scanner.close();
}
}// End of main Method
/**
* Method that prints menu to screen and gets returns user\'s option from menu
* @return Returns user Option
*/
public static int showMenu() {
// Declaring var for user option and defaulting to 0
int option = 0;
// Printing menu to screen
System.out.println(\"Menu:\");
System.out.println(\"1.Hard Problem\");
System.out.println(\"2.Easy Problem\");
System.out.println(\"3. Quit\");
// Getting user option from above menu
System.out.println(\"Enter Option from above...\");
option = scanner.nextInt();
return option;
}
public static ListcreateListOfNames(){
ListnameList=new ArrayList();
System.out.println(\"Enter the number of children to enter\");
int num=scanner.nextInt();
for(int i=0;inameList){
int correctAnswers=0;
int day=0;
for(String name:nameList){
boolean correct=false;
int index=day%nameList.size();
String childForDishDuty=nameList.get(index);
System.out.println(\"Please enter the child name\");
String userInput=scanner.next();
if(childForDishDuty.equalsIgnoreCase(userInput)){
correct=true;
}
if(correct){
correctAnswers++;
}
day++;
}
return correctAnswers;
}
public static int easyProblem(ListnameList){
int correctAnswers=0;
int day=0;
for(String name:nameList){
boolean correct=false;
int index=day%nameList.size();
String childForDishDuty=\"Day \"+day+\":\"+nameList.get(index)+\" must do the
dishes\";
System.out.println(childForDishDuty);
System.out.println(\"Please enter the child name\");
String userInput=scanner.next();
if(nameList.get(index).equalsIgnoreCase(userInput)){
correct=true;
}
if(correct){
correctAnswers++;
}
day++;
}
return correctAnswers;
}
}
Solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Demo {
static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
ListnameList=createListOfNames();
try {
// Declare variable for user\'s option
int .
In 2008 Android app code had a lot of boilerplate, and was very error prone.
More code.. more bugs!
Now it doesn't have to be... but that is an option that each developer needs to take!
Java programI made this Account.java below. Using the attached cod.pdffathimafancy
Java program
I made this Account.java below. Using the attached code I need help with 10.7 (Game: ATM
machine)
Use the Account class created in Programming Exercise 9.7 to simulate an ATM machine.
Create ten accounts in an array with id 0, 1, . . . , 9, and initial balance $100.
The system prompts the user to enter an id. If the id is entered incorrectly, ask the user to enter a
correct id.
Once an id is accepted, the main menu is displayed as shown in the sample run.
You can enter a choice 1 for viewing the current balance, 2 for withdrawing money, 3 for
depositing money, and 4 for exiting the main menu.
Once you exit, the system will prompt for an id again. Thus, once the system starts, it will not
stop.
*/
import java.util.Date;
public class Account {
/**
* @param args
*/
private int id=0;
private double balance=0;
private double annualIntrestRate=0;
private Date dateCreated;
public Account() {
super();
}
public Account(int id, double balance) {
super();
this.id = id;
this.balance = balance;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualIntrestRate() {
return annualIntrestRate;
}
public void setAnnualIntrestRate(double annualIntrestRate) {
this.annualIntrestRate = annualIntrestRate;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public double getMonthlyInterestRate()
{
return (this.getAnnualIntrestRate()/12);
}
public double getMonthlyInterest()
{
return (getBalance() *getMonthlyInterestRate()/100);
}
public double withDraw(double balance)
{
this.setBalance(this.getBalance()-balance);
return this.getBalance();
}
public double diposite(double balance)
{
this.setBalance(this.getBalance()+balance);
return this.getBalance();
}
public double totalBalance()
{
balance =balance + getMonthlyInterest();
return balance;
}
}
//AccountTest.java
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class AccountTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
Account ac=new Account(1,5000.00);
System.out.println(\"Enter the annual intrest rate\");
double intrestRate=sc.nextDouble();
ac.setAnnualIntrestRate(intrestRate);
Date d=new Date();
Calendar currentDate = Calendar.getInstance();
ac.setDateCreated(currentDate.getTime());
System.out.println(\"Date id \"+ac.getDateCreated());
System.out.println(\"Monthly intrest rate is :\"+ac.getMonthlyInterestRate());
System.out.println(\"Monthly intrest is :\"+ac.getMonthlyInterest());
System.out.println(\"Enter Amount for diposite \");
double dipositeAmount=sc.nextDouble();
System.out.println(\"The amount after diposite is :\"+ac.diposite(dipositeAmount));
System.out.println(\"Enter Amount to withdraw :\");
double withdramount= sc.nextDouble.
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
pH = pKa + log (Sa) where S =moles of salt a = m.pdfanujsharmaanuj14
pH = pKa + log (S/a) where S =moles of salt a = moles of acid pH = 4.745 + log
(0.025 / 0.1) = 4.143
Solution
pH = pKa + log (S/a) where S =moles of salt a = moles of acid pH = 4.745 + log
(0.025 / 0.1) = 4.143.
H is reduced, while Fe is oxidized. Note the oxi.pdfanujsharmaanuj14
H is reduced, while Fe is oxidized. Note: the oxidation state of H changes from +1
In HI to 0 in H2. the oxidation state of Fe changes from 0 in Fe(CO)5 to +2 in Fe(CO)4I2. CO is
a neutral ligand.
Solution
H is reduced, while Fe is oxidized. Note: the oxidation state of H changes from +1
In HI to 0 in H2. the oxidation state of Fe changes from 0 in Fe(CO)5 to +2 in Fe(CO)4I2. CO is
a neutral ligand..
Ionization energy is the energy required to remove theouter most ele.pdfanujsharmaanuj14
Ionization energy is the energy required to remove theouter most electron from the gaseous
atom.
The electronic configuration (E.C.) of O (8) is [He]2s2 2p4
The electronic configuration (E.C.) of S (16) is [Ne]3s2 3p4
The electronic configuration (E.C.) of S (16) is [Ne]3s2 3p4
The electronic configuration (E.C.) of P (15) is [Ne]3s2 3p3
The electronic configuration (E.C.) of Al (13) is [Ne]3s2 3p1
The electronic configuration (E.C.) of K(19) is [Ar]4s1
The electronic configuration (E.C.) of Na (11) is [Ne]3s1
1)O & S belongs to same group so on moving from top tobottom atomc size increases ,so for the
removal of e- from S iseasier than O ==> ionization energy is more for O
2)Na &K belongs to same group so on moving from topto bottom atomc size increases ,so for the
removal of e- from K iseasier than Na ==> ionization energy is more for Na
3) Na, Al , & P beleong to the same period.On moving fromleft to right the atomic size will
decreases due the morenuclear charge.So to remove the e- from P is more than that of Alwhich in
ture is more than Na
4)Among P & S , P has half filled configuration of porbitals so more stable than S .Therefore
more energy for P thanS
So the overall order of the ionization energy is O >P > S > Al > Na > K
1)O & S belongs to same group so on moving from top tobottom atomc size increases ,so for the
removal of e- from S iseasier than O ==> ionization energy is more for O
2)Na &K belongs to same group so on moving from topto bottom atomc size increases ,so for the
removal of e- from K iseasier than Na ==> ionization energy is more for Na
3) Na, Al , & P beleong to the same period.On moving fromleft to right the atomic size will
decreases due the morenuclear charge.So to remove the e- from P is more than that of Alwhich in
ture is more than Na
4)Among P & S , P has half filled configuration of porbitals so more stable than S .Therefore
more energy for P thanS
So the overall order of the ionization energy is O >P > S > Al > Na > K
Solution
Ionization energy is the energy required to remove theouter most electron from the gaseous
atom.
The electronic configuration (E.C.) of O (8) is [He]2s2 2p4
The electronic configuration (E.C.) of S (16) is [Ne]3s2 3p4
The electronic configuration (E.C.) of S (16) is [Ne]3s2 3p4
The electronic configuration (E.C.) of P (15) is [Ne]3s2 3p3
The electronic configuration (E.C.) of Al (13) is [Ne]3s2 3p1
The electronic configuration (E.C.) of K(19) is [Ar]4s1
The electronic configuration (E.C.) of Na (11) is [Ne]3s1
1)O & S belongs to same group so on moving from top tobottom atomc size increases ,so for the
removal of e- from S iseasier than O ==> ionization energy is more for O
2)Na &K belongs to same group so on moving from topto bottom atomc size increases ,so for the
removal of e- from K iseasier than Na ==> ionization energy is more for Na
3) Na, Al , & P beleong to the same period.On moving fromleft to right the atomic size will
decreases due the morenuclear charge.So to remove the e- .
The presence of conjugated Carbon-carbon double bonds causes colorat.pdfanujsharmaanuj14
The presence of conjugated Carbon-carbon double bonds causes coloration. When those bonds
are broken, the color fades.
Solution
The presence of conjugated Carbon-carbon double bonds causes coloration. When those bonds
are broken, the color fades..
The amount to be deposited at the start of his studies is found as.pdfanujsharmaanuj14
The amount to be deposited at the start of his studies is found as
PV = C [ 1 - ( 1+r)-2 / r ] x ( 1+r)-t
PV = $ 12,300 [ 1 - ( 1+0.06)-2 / 0.06 ] x( 1+0.06) -1
PV = 21,274
Solution
The amount to be deposited at the start of his studies is found as
PV = C [ 1 - ( 1+r)-2 / r ] x ( 1+r)-t
PV = $ 12,300 [ 1 - ( 1+0.06)-2 / 0.06 ] x( 1+0.06) -1
PV = 21,274.
SolutionNet cash provided by operating activities for the year end.pdfanujsharmaanuj14
Solution
Net cash provided by operating activities for the year ended December 31, 2014
Eliminate
Depreciation expense
+80000
Adjust revenue and expenses from accrual
accounting to cashNet income151490
Eliminate
Depreciation expense
+80000
Adjust revenue and expenses from accrual
accounting to cashIncrease in account receivable(20370)Decrease in inventory+12840Increase in
prepaid expenses(4370)Decrease in account payable(6480)Increase in accrued expenses
payable+11240Total cash generated by operating activities224360.
SOA ( Service Oriented Architecture)SOA is a type of architectura.pdfanujsharmaanuj14
SOA ( Service Oriented Architecture):
SOA is a type of architectural pattern in computer software design where application
components provides services to other components via network.This removes the need for third
party product,vendor or technology.
The main functionality to this type of model is to make it easier for software components
connected over the internet to communicate with each other without human interaction.so every
computer can run any number of services and this can be archeived without changing the main
program itself.SOA provides a cost effective way to evolve and enhance Enterprise information
systems.
Web 2.0 on the other hand is world wide web websites that emphasize user-generated
content,interoperability for end users. Some have agreed that web 2.0 is the best form of
realizing SOA.
1)-2) Interoperability and portability:
SOA can be realized through the help of webservices, because the best characterstic of
webservices is the interoperability.Different distributed web services run on variety of software
platforms and hardware architectures.JAVA j2EE and java WSDP are the best examples.
3) Platform independence:
For example take a case where XML,XML schema are there which are used to
publish,describe,search information. and there are multiple technologies and versions like SOAP,
WSDL, UDDI, and ebXML to do this. For the web services to be functional, we need an
environment of platform independent model.For example consider AJAX (asynchronous
javascript and XML) is not a technology, it is just a technique to createinteractive webpages for
this it supports XHTML,CSS,DOM,XML,XSLT,ATOM,SQL,REST,SOAP etc and uses
javascript to glue it all together.This is a perfect example of SOA present in current trend.
Solution
SOA ( Service Oriented Architecture):
SOA is a type of architectural pattern in computer software design where application
components provides services to other components via network.This removes the need for third
party product,vendor or technology.
The main functionality to this type of model is to make it easier for software components
connected over the internet to communicate with each other without human interaction.so every
computer can run any number of services and this can be archeived without changing the main
program itself.SOA provides a cost effective way to evolve and enhance Enterprise information
systems.
Web 2.0 on the other hand is world wide web websites that emphasize user-generated
content,interoperability for end users. Some have agreed that web 2.0 is the best form of
realizing SOA.
1)-2) Interoperability and portability:
SOA can be realized through the help of webservices, because the best characterstic of
webservices is the interoperability.Different distributed web services run on variety of software
platforms and hardware architectures.JAVA j2EE and java WSDP are the best examples.
3) Platform independence:
For example take a case where XML,XML schema are there which are used to
publis.
Nt = No er twhere density at time tNo= = starting densityNr=dN.pdfanujsharmaanuj14
Nt = No er t
where density at time t
No= = starting density
Nr=dN/dt so r=1/N*dN/dt
t =1
1):- Nt = No er t
if No =1
=1* e-.1*1
=9.047
2):- Nt = No er t
if No=3
=3* e0.1*1=1.105*3=3.3156
3):-Nt = No er t
if No=7=
7*e0.37*1=10.08
4):-Nt = No er t
if No=14
=14*e-0.3*1=10.36
Solution
Nt = No er t
where density at time t
No= = starting density
Nr=dN/dt so r=1/N*dN/dt
t =1
1):- Nt = No er t
if No =1
=1* e-.1*1
=9.047
2):- Nt = No er t
if No=3
=3* e0.1*1=1.105*3=3.3156
3):-Nt = No er t
if No=7=
7*e0.37*1=10.08
4):-Nt = No er t
if No=14
=14*e-0.3*1=10.36.
Normalization is necessay step in creation of database design becaus.pdfanujsharmaanuj14
Normalization is necessay step in creation of database design because:
Solution
Normalization is necessay step in creation of database design because:.
Hi, Please find my codeimport java.util.Random;public class Pro.pdfanujsharmaanuj14
Hi, Please find my code:
import java.util.Random;
public class ProcessArray {
private int rows; //The attribute for number of rows in matrix
private int columns; //The attribute for number of columns in matrix
private int[][] firstArray; //The attribute for the first array
private int[][] secondArray; //The attribute for the second array
public int[][] getFirstArray() { return firstArray;}
public int[][] getSecondArray() { return secondArray;}
public ProcessArray(int rows, int columns){ //Constructor of object ProcessArray
this.rows = rows;
this.columns = columns;
int[][] array = new int[rows][columns];
initializeArray(array);
randomlyFillArray();
computeArrayValues();
printArray(secondArray);
}
public void initializeArray(int[][] array){ //Initializes first and second arrays and sets each value
to 0
firstArray = new int[rows][columns];
secondArray = new int[rows][columns];
}
public void randomlyFillArray(){ //Fills first array with random numbers
for(int i = 0; i < firstArray.length;i++){
for(int j = 0; j < firstArray[0].length;j++){
Random r = new Random();
int num = r.nextInt(16);
firstArray[i][j] = num;
}
}
}
public void computeArrayValues(){
int col = firstArray[0].length;
int row = firstArray.length;
for(int i = 0; i < row; i++){
for(int j = 0; j< col; j++){
secondArray[i][j] = 0;
if((i - 1) >=0){
secondArray[i][j] += firstArray[i-1][j];
if((j+1) < col)
secondArray[i][j] += firstArray[i-1][j+1];
if(j > 0)
secondArray[i][j] += firstArray[i-1][j-1];
}
if((j+1) < col)
secondArray[i][j] += firstArray[i][j+1];
if(j > 0)
secondArray[i][j] += firstArray[i][j-1];
if((i+1) < row){
secondArray[i][j] += firstArray[i+1][j];
if((j+1) < col)
secondArray[i][j] += firstArray[i+1][j+1];
if(j > 0)
secondArray[i][j] += firstArray[i+1][j-1];
}
}
}
}
public void printArray(int[][] Array){
System.out.println(\"\ Initial Array Filled With Random Numbers: \ \");
for(int a = 0; a < firstArray.length; a++){
for(int b = 0; b < firstArray[0].length; b++){
if(b == 0)
System.out.printf(\"%d \", firstArray[a][b]);
else
System.out.printf(\"%d \", firstArray[a][b]);
}System.out.println();
}System.out.println();
System.out.println(\"Computed Array: \ \");
for(int a = 0; a < secondArray.length; a++){
for(int b = 0; b < secondArray[0].length; b++){
if(b == 0)
System.out.printf(\"%d \", secondArray[a][b]);
else
System.out.printf(\"%d \", secondArray[a][b]);
}
System.out.println();
}System.out.println();
}
public static void main(String[] args) {
ProcessArray pr = new ProcessArray(3, 4);
}
}
/*
Sample Output:
Initial Array Filled With Random Numbers:
7 3 6 12
10 2 11 10
12 14 1 7
Computed Array:
15 36 38 27
38 64 55 37
26 36 44 22
*/
Solution
Hi, Please find my code:
import java.util.Random;
public class ProcessArray {
private int rows; //The attribute for number of rows in matrix
private int columns; //The attribute for number of columns in matrix
private int[][] firstArray; //The attribute for the first array
private int[][] secondArray; //The attribute for the second arr.
For sound intensity,ratio in dB is given byx = 10log(IIo)We.pdfanujsharmaanuj14
For sound intensity,
ratio in dB is given by:
x = 10*log(I/Io)
We know, I = P/(4*pi*D^2) <----- I is inversely proportional to D
So, x = 10*log(D^2/(D+d)^2)
where D = original distance from speaker
d = distance he has moved from original distance from speaker
So, -14 = 10*log((D/(D+d))^2)
So, (D+d)/D = 5.01
So, 1 + d/D = 5.01
So, d/D = 4.01
So, d = 4.01*D <-------- So, he is about 4.01 times D away from original distance or 5.01*D
distance away from speaker
So, answer is : 5.01*D
Solution
For sound intensity,
ratio in dB is given by:
x = 10*log(I/Io)
We know, I = P/(4*pi*D^2) <----- I is inversely proportional to D
So, x = 10*log(D^2/(D+d)^2)
where D = original distance from speaker
d = distance he has moved from original distance from speaker
So, -14 = 10*log((D/(D+d))^2)
So, (D+d)/D = 5.01
So, 1 + d/D = 5.01
So, d/D = 4.01
So, d = 4.01*D <-------- So, he is about 4.01 times D away from original distance or 5.01*D
distance away from speaker
So, answer is : 5.01*D.
Exp- Listeria monocytogenes is a facultative anaerobic bacteria tha.pdfanujsharmaanuj14
Exp:- Listeria monocytogenes is a facultative anaerobic bacteria that can survive both aerobic
and anaerobic conditions and is responsible for listeriosis disease. The bacterium can undergo
fermentation in absence of oxygen and normal glycolysis and Krebs cycle.The main route of
infection is ingestion of contaminated food.
Solution
Exp:- Listeria monocytogenes is a facultative anaerobic bacteria that can survive both aerobic
and anaerobic conditions and is responsible for listeriosis disease. The bacterium can undergo
fermentation in absence of oxygen and normal glycolysis and Krebs cycle.The main route of
infection is ingestion of contaminated food..
DNA controversy is a dispute about whether Rosalind Franklin and Wil.pdfanujsharmaanuj14
DNA controversy is a dispute about whether Rosalind Franklin and Wilkins were given proper
credit for their contribution to the determination of the structure of DNA. In January 1951,
Franklin discovered that there were two forms of DNA by using x-ray diffraction techniques, she
worked as a research associate at King\'s College London in the Medical Research Council\'s
Biophysics Unit. The controversy arose from claims that some of the data were shown to Watson
and Crick, without her knowledge. Her experimental results provided estimates of the water
content of DNA crystals and these reults were consistent with the two sugar-phosphate
backbones being on the outside of the molecule. Franklin personallytold Crick and Watson that
hte X-ray diffraction images collected where the best evidence for the helical nature od DNA.
Crick and Waatson had been to the public seminar presented by Franklin, where they had spoken
to Wilkins about offering him a co-authorship on the article that first described the double helix
structure of DNA. On the completion of their model, Crick and Watson had invited Wilkins to be
a co-author of the paper describing the structure, he turned down this offer as he had taken no
part in building the model. Watson, Francis Crick and Maurice Wilkins were awarded the 1962
Nobel Prize for Physiology or Medicine for their discoveries concerning the molecular structure
of nucleic acids and its significance for information transfer in living material, with the help of
the research of Rosalind Franklin.
There is a little doubt that the significance of Franklin\'s data should have been acknowledged-
the evidence is overwhelming that it played an important role in Watson and Crick\'s modelling
process. Franklin could not share in the 1962 Nobel prize awarded to Watson and Crick because
she had died of ovarian cancer in 1958. Hence, it cannot be concluded that Watson and Crick
were not ethical about their research and also that they donot deserve a nobel prize for their
discovery. And the Historical records contain all the data of the work presented by Franklin and
also by Watson and Crick.
Solution
DNA controversy is a dispute about whether Rosalind Franklin and Wilkins were given proper
credit for their contribution to the determination of the structure of DNA. In January 1951,
Franklin discovered that there were two forms of DNA by using x-ray diffraction techniques, she
worked as a research associate at King\'s College London in the Medical Research Council\'s
Biophysics Unit. The controversy arose from claims that some of the data were shown to Watson
and Crick, without her knowledge. Her experimental results provided estimates of the water
content of DNA crystals and these reults were consistent with the two sugar-phosphate
backbones being on the outside of the molecule. Franklin personallytold Crick and Watson that
hte X-ray diffraction images collected where the best evidence for the helical nature od DNA.
Crick and Waatson had .
Delta is a measures of the change in price of an option for a one po.pdfanujsharmaanuj14
Delta is a measures of the change in price of an option for a one point move in the underlying
asset. Delta measure the price sensitivity of underlying assets.
Option (A) is correct answer.
Solution
Delta is a measures of the change in price of an option for a one point move in the underlying
asset. Delta measure the price sensitivity of underlying assets.
Option (A) is correct answer..
consider the cross between White petals and dark blue petalsFlower.pdfanujsharmaanuj14
consider the cross between White petals and dark blue petals
Flower color in sweet peas.
Sweet peas - is the classic object of genetic research of traits inheritance. When scientists studied
the color of flowers of this plant, they discover, that in some crosses the ratio of phenotype was
9:7. That is, from the crossing of two pure lines of sweet peas with white flowers, all plants in
first-generation had the purple flowers. And from crossing of these hybrids was obtained the
offspring with the phenotypic ratio : 9 purple: 7 white. If the ratio was 3:1, we could suppose,
that we are dealing with a simple monohybrid crossing, but in this case the ratio is differ. So
obviously, the genetic trait of color of sweet peas flowers is controlled by two nonallelic genes,
which interact each other. For convenience, we mark these genes as \"C\" and \"P\". Thus, the
pure lines will have genotypes \"CCpp\" and \"ccPP\", and first generation hybrids respectively
genotype \"CcPp\". The mechanism of genetic interaction of these genes has become known
recently. It was found that the color of sweet pea flowers depends on the synthesis of pigments -
anthocyanins. The synthesis of anthocyanins occurs in two stages. Gene \"C\" is responsible for
the first stage of the synthesis, while the gene \"P\" for second, and even if only one dominant
allele from these genes is lack, then synthesis of anthocyanins is not occurs. That is to say, that
the presence of a recessive allele in the homozygous state in the genotype of either of the two
genes is blocks the development of trait of flowers coloration. Such interaction of nonallelic
genes is called a double recessive epistasis. We can describe this interaction like this - recessive
allele of each gene in the homozygous state suppresses the expression of a dominant allele of
another ( \"cc\" suppresses \"P\", \"pp\" suppresses \"C\" ). Genetic traits file for this case should
be like this :
Solution
consider the cross between White petals and dark blue petals
Flower color in sweet peas.
Sweet peas - is the classic object of genetic research of traits inheritance. When scientists studied
the color of flowers of this plant, they discover, that in some crosses the ratio of phenotype was
9:7. That is, from the crossing of two pure lines of sweet peas with white flowers, all plants in
first-generation had the purple flowers. And from crossing of these hybrids was obtained the
offspring with the phenotypic ratio : 9 purple: 7 white. If the ratio was 3:1, we could suppose,
that we are dealing with a simple monohybrid crossing, but in this case the ratio is differ. So
obviously, the genetic trait of color of sweet peas flowers is controlled by two nonallelic genes,
which interact each other. For convenience, we mark these genes as \"C\" and \"P\". Thus, the
pure lines will have genotypes \"CCpp\" and \"ccPP\", and first generation hybrids respectively
genotype \"CcPp\". The mechanism of genetic interaction of these genes has bec.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Vehicle.javapublic class Vehicle { Declaring instance var.pdf
1. Vehicle.java
public class Vehicle
{
//Declaring instance variables
private int max_no_passengers;
private int top_speed;
private double miles_travelled;
//Parameterized constructor
public Vehicle(int max_no_passengers, int top_speed, double miles_travelled) {
super();
this.max_no_passengers = max_no_passengers;
this.top_speed = top_speed;
this.miles_travelled = miles_travelled;
}
//Getters and setters
public int getMax_no_passengers() {
return max_no_passengers;
}
public void setMax_no_passengers(int max_no_passengers) {
this.max_no_passengers = max_no_passengers;
}
public int getTop_speed() {
return top_speed;
}
public void setTop_speed(int top_speed) {
this.top_speed = top_speed;
}
public double getMiles_travelled() {
return miles_travelled;
}
public void setMiles_travelled(double miles_travelled) {
this.miles_travelled = miles_travelled;
}
2. /* This getInfor() method returns the information about this vehicle class object
* Params: void
* Return:String
*/
public String getInfo()
{
String str=" Maximum No of Passengers :"+getMax_no_passengers()+
" Top Speed :"+getTop_speed()+
" Total Miles Travelled :"+getMiles_travelled();
return str;
}
}
_____________________________________________
FoodTruck.java
import java.util.ArrayList;
public class FoodTruck extends Vehicle{
//Declaring instance variables
private String name;
private ArrayList menu;
//Parameterized constructor
public FoodTruck(int max_no_passengers, int top_speed,
double miles_travelled, String name, ArrayList menu) {
super(max_no_passengers, top_speed, miles_travelled);
this.name = name;
this.menu = menu;
}
//Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList getMenu() {
3. return menu;
}
public void setMenu(ArrayList menu) {
this.menu = menu;
}
/* This getInfor() method returns the information about this Food truck class Object
* And also the information about the Vehicle class Object.
* Params: void
* Return:String
*/
@Override
public String getInfo() {
String str="Food Truck Name : "+name+
" Menu of items : "+menu+super.getInfo();
return str;
}
}
________________________________________________
Test.java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//Creating an ArrayList Object which holds List of Menu Items
ArrayList menu1=new ArrayList();
//Adding menu items to the ArrayList
menu1.add("Burger");
menu1.add("Pizza");
menu1.add("Chips");
//Creating FoodTruck Object by passing parameters.
FoodTruck truck1=new FoodTruck(15,100,10000,"Mobile Food Court",menu1);
//Displaying the Truck1 Information.
4. System.out.println("__________Truck 1 Details__________");
System.out.println(truck1.getInfo());
//Creating an ArrayList Object which holds List of Menu Items
ArrayList menu2=new ArrayList();
//Adding menu items to the ArrayList
menu2.add("Tea");
menu2.add("Coffe");
menu2.add("Cool Drinks");
//Creating FoodTruck Object by passing parameters.
FoodTruck truck2=new FoodTruck(10,80,5000,"Drinks Van",menu2);
//Displaying the Truck2 Information.
System.out.println(" __________Truck 2 Details__________");
System.out.println(truck2.getInfo());
//Creating an ArrayList Object which holds List of Menu Items
ArrayList menu3=new ArrayList();
//Adding menu items to the ArrayList
menu3.add("ChocoBar");
menu3.add("Black Forest");
menu3.add("Butter Scortch");
//Creating FoodTruck Object by passing parameters.
FoodTruck truck3=new FoodTruck(12,85,15000,"Ice Cream Court",menu3);
//Displaying the Truck3 Information.
System.out.println(" __________Truck 3 Details__________");
System.out.println(truck3.getInfo());
}
}
_____________________________________________
Output:
5. __________Truck 1 Details__________
Food Truck Name : Mobile Food Court
Menu of items : [Burger, Pizza, Chips]
Maximum No of Passengers :15
Top Speed :100
Total Miles Travelled :10000.0
__________Truck 2 Details__________
Food Truck Name : Drinks Van
Menu of items : [Tea, Coffe, Cool Drinks]
Maximum No of Passengers :10
Top Speed :80
Total Miles Travelled :5000.0
__________Truck 1 Details__________
Food Truck Name : Ice Cream Court
Menu of items : [ChocoBar, Black Forest, Butter Scortch]
Maximum No of Passengers :12
Top Speed :85
Total Miles Travelled :15000.0
_____________________________________________Thank You
Solution
Vehicle.java
public class Vehicle
{
//Declaring instance variables
private int max_no_passengers;
private int top_speed;
private double miles_travelled;
//Parameterized constructor
public Vehicle(int max_no_passengers, int top_speed, double miles_travelled) {
super();
this.max_no_passengers = max_no_passengers;
this.top_speed = top_speed;
this.miles_travelled = miles_travelled;
6. }
//Getters and setters
public int getMax_no_passengers() {
return max_no_passengers;
}
public void setMax_no_passengers(int max_no_passengers) {
this.max_no_passengers = max_no_passengers;
}
public int getTop_speed() {
return top_speed;
}
public void setTop_speed(int top_speed) {
this.top_speed = top_speed;
}
public double getMiles_travelled() {
return miles_travelled;
}
public void setMiles_travelled(double miles_travelled) {
this.miles_travelled = miles_travelled;
}
/* This getInfor() method returns the information about this vehicle class object
* Params: void
* Return:String
*/
public String getInfo()
{
String str=" Maximum No of Passengers :"+getMax_no_passengers()+
" Top Speed :"+getTop_speed()+
" Total Miles Travelled :"+getMiles_travelled();
return str;
}
}
_____________________________________________
FoodTruck.java
import java.util.ArrayList;
7. public class FoodTruck extends Vehicle{
//Declaring instance variables
private String name;
private ArrayList menu;
//Parameterized constructor
public FoodTruck(int max_no_passengers, int top_speed,
double miles_travelled, String name, ArrayList menu) {
super(max_no_passengers, top_speed, miles_travelled);
this.name = name;
this.menu = menu;
}
//Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList getMenu() {
return menu;
}
public void setMenu(ArrayList menu) {
this.menu = menu;
}
/* This getInfor() method returns the information about this Food truck class Object
* And also the information about the Vehicle class Object.
* Params: void
* Return:String
*/
@Override
public String getInfo() {
String str="Food Truck Name : "+name+
" Menu of items : "+menu+super.getInfo();
return str;
8. }
}
________________________________________________
Test.java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//Creating an ArrayList Object which holds List of Menu Items
ArrayList menu1=new ArrayList();
//Adding menu items to the ArrayList
menu1.add("Burger");
menu1.add("Pizza");
menu1.add("Chips");
//Creating FoodTruck Object by passing parameters.
FoodTruck truck1=new FoodTruck(15,100,10000,"Mobile Food Court",menu1);
//Displaying the Truck1 Information.
System.out.println("__________Truck 1 Details__________");
System.out.println(truck1.getInfo());
//Creating an ArrayList Object which holds List of Menu Items
ArrayList menu2=new ArrayList();
//Adding menu items to the ArrayList
menu2.add("Tea");
menu2.add("Coffe");
menu2.add("Cool Drinks");
//Creating FoodTruck Object by passing parameters.
FoodTruck truck2=new FoodTruck(10,80,5000,"Drinks Van",menu2);
//Displaying the Truck2 Information.
9. System.out.println(" __________Truck 2 Details__________");
System.out.println(truck2.getInfo());
//Creating an ArrayList Object which holds List of Menu Items
ArrayList menu3=new ArrayList();
//Adding menu items to the ArrayList
menu3.add("ChocoBar");
menu3.add("Black Forest");
menu3.add("Butter Scortch");
//Creating FoodTruck Object by passing parameters.
FoodTruck truck3=new FoodTruck(12,85,15000,"Ice Cream Court",menu3);
//Displaying the Truck3 Information.
System.out.println(" __________Truck 3 Details__________");
System.out.println(truck3.getInfo());
}
}
_____________________________________________
Output:
__________Truck 1 Details__________
Food Truck Name : Mobile Food Court
Menu of items : [Burger, Pizza, Chips]
Maximum No of Passengers :15
Top Speed :100
Total Miles Travelled :10000.0
__________Truck 2 Details__________
Food Truck Name : Drinks Van
Menu of items : [Tea, Coffe, Cool Drinks]
Maximum No of Passengers :10
Top Speed :80
Total Miles Travelled :5000.0
__________Truck 1 Details__________
Food Truck Name : Ice Cream Court
Menu of items : [ChocoBar, Black Forest, Butter Scortch]
10. Maximum No of Passengers :12
Top Speed :85
Total Miles Travelled :15000.0
_____________________________________________Thank You