Showing posts with label class. Show all posts
Showing posts with label class. Show all posts

Computing the polynomial mathematical function in java

Problem:

A polynomial function is a very famous mathematical function.
The greatest exponent, n, is called the degree of the polynomial. For example, p(x) = 7x4 2 is a
polynomial of degree 4. The simplest polynomials are constant polynomials such as p(x) = 6
(degree 0) and linear polynomials such as p(x) = 9x + 6 (degree 1). The unique zero polynomial
p(x) = 0 is defined to have degree 1. In this section we present a Polynomial class whose
instances represent mathematical polynomials and which supports the usual algebraic operations
on polynomials.
A polynomial can be regarded as a sum of distinct terms. A term is a mathematical function of
the form t (x) = cxe, where c is any real number and e is any nonnegative integer. The number c is
called the coefficient, and the number e is called the exponent.
To define a class whose objects represent polynomials, we use a linked list of Term objects.
For example, the polynomial p(x) = 3x2 2x + 5 could be represented as a list of three elements,
where the first element represents the term 3x2, the second element represents the term 2x, and
the third element represents the (constant) term 5.

Write a java program that computes the polynomial function.

Output:

Not applicable

Solution:

public class Polynomial {
private List<Term> list = new LinkedList<Term>();
public static final Polynomial ZERO = new Polynomial();
private Polynomial() { // default constructor
}
public Polynomial(double coef, int exp) {
if (coef != 0.0) {
list.add(new Term(coef, exp));
}
}
public Polynomial(Polynomial p) { // copy constructor
for (Term term : p.list) {
this.list.add(new Term(term));
}
}
public Polynomial(double... a) {
for (int i=0; i<a.length; i++) {
if (a[i] != 0.0) {
list.add(new Term(a[i], i));
}
}
}
public int degree() {
if (list.isEmpty()) {
return -1;
} else {
return list.get(list.size()-1).exp;
}
public boolean isZero() {
return list.isEmpty();
}
public Polynomial plus(Polynomial p) {
if (this.isZero()) {
return new Polynomial(p);
}
if (p.isZero()) {
return new Polynomial(this);
}
Polynomial q = new Polynomial();
ListIterator<Term> it = list.listIterator();
ListIterator<Term> itp = p.list.listIterator();
while (it.hasNext() && itp.hasNext()) {
Term term = it.next();
Term pTerm = itp.next();
if (term.exp < pTerm.exp) {
q.list.add(new Term(term));
itp.previous();
} else if (term.exp == pTerm.exp) {
q.list.add(new Term(term.coef + pTerm.coef, term.exp));
} else { // (term.exp > pTerm.exp)
q.list.add(new Term(pTerm));
it.previous();
}
}
while (it.hasNext()) {
q.list.add(new Term(it.next()));
}
while (itp.hasNext()) {
q.list.add(new Term(itp.next()));
}
return q;
}
public String toString() {
if (this.isZero()) {
return "0";
}
Iterator<Term> it = list.iterator();
StringBuilder buf = new StringBuilder();
boolean isFirstTerm = true;
while (it.hasNext()) {
Term term = it.next();
double c = term.coef;
int e = term.exp;
if (isFirstTerm) {
buf.append(String.format("%.2f", c));
isFirstTerm = false;
} else {
if (term.coef < 0) {
buf.append(String.format(" - %.2f", -c));
} else {
buf.append(String.format(" + %.2f", c));
}
}
if (e == 1) {
buf.append("x");
} else if (e > 1) {
buf.append("x^" + e);
}
}
return buf.toString();
}
private static class Term {
private double coef;
private int exp;
public Term(double coef, int exp) {
if (coef == 0.0 || exp < 0) {
throw new IllegalArgumentException();
}
this.coef = coef;
this.exp = exp;
}
public Term(Term that) { // copy constructor
this(that.coef, that.exp);
}
}
}
Read More

Translate ADT into Java Interface Example

Problem:

Translate this ADT into a Java interface:
ADT: Point
amplitude(): Real
distanceTo(Point): Real
equals(Point): Boolean
magnitude(): Real
toString(): String
xCoordinate(): Real
yCoordinate(): Real

Output:

None

Solution:

public interface Point {
 public double amplitude();
 public double distanceTo(Point point);
 public boolean equals(Object object);
 public double magnitude();
 public String toString();
 public double xCoordinate();
 public double yCoordinate();
}
Read More

Creating an Inheritance program in Java

Problem:

Create a class called Client that has the ID (int), First Name, Last Name (Strings), and amount(double) variables, and the AddMoney(), SubMoney() methods that are responsible respectively to add or subtract money to/from the amount.

Create a class called GoldenClient that inherits from the Client class, but have one more attribute which is char GoldenLevel that can be either ‘H’, ‘M’ or ‘L’. The GoldenLevel is set in method setGoldenLevel() method according to: ‘H’ if amount > 10000, ‘M’ if 5000 < amount < 10000, and ‘L’ if amount < 1000.

Create a class called PlatinumClient that inherits from the Client class, but have two more attributes: int numberOfTrips and double TravelOffersRate. It also has a method called addTrips(int n) that adds n trips to numberOfTrips. TravelOffersRate is calculated according to the formula: numberOfTrips*0.01. Make sure to update the value of TravelOffersRate when addTrips(int n) method adds trips to numberOfTrips.

Make sure to declare all Client’s variables as protected to allow inheritance.

Make sure to include the set, get and toString() methods in all classes. A toString() method will print the variable names and their corresponding values.

At the end, create the main class that contains the main method, create a new user and do some transactions.

Output:

Not needed.

Solution:

/**----------------------------Client.java--------------------*/
public class Client {
 
 protected int id;
 protected String firstName;
 protected String lastName;
 protected double amount;
 
 public Client(int id, String firstName, String lastName, 
                                                double amount) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
  this.amount = amount;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public double getAmount() {
  return amount;
 }

 public void setAmount(double amount) {
  this.amount = amount;
 }
 
 public void addMoney(int toAdd) {
  amount += toAdd;
 }
 
 public void subMoney(int toSub) {
  amount -= toSub;
 }
 
 public String toString() {
  return "ID: "+id+"\nName: "+firstName+" "+
                          lastName+"\nAmount: "+amount+"\n";
 }
}
/**-----------------------ClientTest.java-----------------*/
public class ClientTest {
 
 public static void main(String args[]) {
  Client client = new Client(1, "Jon", "Snow", 10);
  GoldenClient goldenClient = new GoldenClient(2,
                                   "Jaime", "Lannister", 20000);
  PlatinumClient platClient = new PlatinumClient(5,
                                    "Arya", "Stark", 10000, 50);
  
  System.out.println(client);
  System.out.println(goldenClient);
  System.out.println(platClient);
  
  client.addMoney(1000000);
  client.subMoney(50000);
  
  goldenClient.subMoney(13000);
  goldenClient.setGoldenLevel();
  
  platClient.addTrips(10);
  
  System.out.println(client);
  System.out.println(goldenClient);
  System.out.println(platClient);
 }
}
/**-------------------GoldenClient.java-----------------*/
public class GoldenClient extends Client {

 private char goldenLevel;
 
 public GoldenClient(int id, String firstName, 
                          String lastName, double amount) {
  super(id, firstName, lastName, amount);
  setGoldenLevel();
 }
 
 public void setGoldenLevel() {
  if (amount > 10000)
   goldenLevel = 'H';
  else if (amount < 10000 && amount > 5000)
   goldenLevel = 'M';
  else if (amount < 1000)
   goldenLevel = 'L';
 }
 
 public char getGoldenLevel() {
  return goldenLevel;
 }
 
 public String toString() {
  return super.toString() + "Golden Level: "+
                                        goldenLevel+"\n";
 }
}
/**------------------PlatinumClient.java--------------*/
public class PlatinumClient extends Client {

 private int numberOfTrips;
 private double travelOffersRate;
 
 public PlatinumClient(int id, String firstName, 
     String lastName, double amount, int numberOfTrips) {
  super(id, firstName, lastName, amount);
  setNumberOfTrips(numberOfTrips);
 }

 public int getNumberOfTrips() {
  return numberOfTrips;
 }

 public void setNumberOfTrips(int numberOfTrips) {
  this.numberOfTrips = numberOfTrips;
  setTravelOffersRate(numberOfTrips*0.01);
 }

 public double getTravelOffersRate() {
  return travelOffersRate;
 }

 public void setTravelOffersRate(double travelOffersRate) {
  this.travelOffersRate = travelOffersRate;
 }

 public void addTrips(int n) {
  numberOfTrips += n;
  travelOffersRate = numberOfTrips*0.01;
 }
 
 public String toString() {
  return super.toString() + "Number of Trips: "+
         numberOfTrips+"\nTravel Offers Rate: "+travelOffersRate+"\n";
 }
}
Read More

Creating a Polymorphism and Histogram Application in Java

Problem:

User
- username : String
- password : String
- items[] : String
+ User(username : String, password : String, items[] : String)
+ setUsername(username : String) : void
+ getUsername() : String
+ setPassword(password : String) : void
+ getPassword() : String
+ setItems(items[] : String) : void
+ getItems() : String[]
# abstract getAccessibleItems() : String[]
+ toString() : String

Admin

+ Admin(username : String, password : String, items[] : String)
+ getAccessibleItems() : String[]
+ toString() : String

AccountingUser

+ AccountingUser(username : String, password : String, items[] : String)
+ getAccessibleItems() : String[]
+ toString() : String




In this assignment, you will be using inheritance and polymorphism to create an admin and an accounting user for some system.
The User class is an abstract class made up of a username, a password, and an array of accessible items. It has setter and getter methods and an abstract method called getAccessibleItems which should be implemented by subclasses of User.
The Admin class and the AccountingUser class are both subclasses of User. This means that you have to use inheritance to create both classes. Each of these classes' constructors must call the superclass constructor. Moreover, both of these classes have to implement the getAccessibleItems method which has to return an array of strings describing the items the user has access to.
Usually, a system admin has access to every item, while another user has access for a limited set of items. For example, the AccountingUser will have access to an accounting related item but not any other item.
Write a tester class which has an array of Users.
The array should contain one Admin and two AccountingUsers. After creating the users, you should loop over the array and use polymorphism to get the accessible items and print the user’s information.
Printing format is as follows:
(username)

Accessible items:
(getAccessibleItems())




Solution:
/**---------------AccountingUser.java--------------*/
public class AccountingUser extends User {

 public AccountingUser(String username, 
                  String password, String[] items) {
  super(username, password, items);
 }

 protected String[] getAccessibleItems() {
  String[] myItems = new String[2];
  
  myItems[0] = "Accounting View";
  myItems[1] = "Invoice View";
  
  return myItems;
 }
}

/**--------------Admin.java--------------------*/
public class Admin extends User {

 public Admin(String username, 
                   String password, String[] items) {
  super(username, password, items);
 }

 protected String[] getAccessibleItems() {
  return getItems();
 }
}
/**--------------User.java--------------------*/
public abstract class User {
 
 private String   username;
 private String   password;
 private String[] items;
 
 public User(String username, String password, 
                                      String[] items) {
  this.username = username;
  this.password = password;
  this.items = items;
 }

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String[] getItems() {
  return items;
 }

 public void setItems(String[] items) {
  this.items = items;
 }

 protected abstract String[] getAccessibleItems();
 
 public String toString() {
  return username+"\n\n";
 }
 
}
/**------------------------Tester.java---------------------*/
public class Tester {

 public static void main(String[] args) {
  
  String[] items = {"Accounting view", 
                "Invoice view", "HR view", "Admin view", 
                "Marketing view", "IT view"};
  
  User[] users = new User[3];
  
  users[0] = new Admin("admin", "admin", items);
  users[1] = new AccountingUser("AccUser", "acc123", items);
  users[2] = new AccountingUser("AccUser2", "123acc", items);
  
  for (int i = 0; i < users.length; i++) {
   
   if(users[i] instanceof Admin) {
    
   Admin currentUser = (Admin) users[i];
   String[] accessibleItems = currentUser.getAccessibleItems();
   System.out.println(currentUser+"Accessible Items:");
   for (int j = 0; j < accessibleItems.length; j++)
   System.out.print(accessibleItems[j] + " ");
    
   } else {
    
   AccountingUser currentUser = (AccountingUser) users[i];
   String[] accessibleItems = currentUser.getAccessibleItems();
   System.out.println(currentUser+"Accessible Items:");
    
   for (int j = 0; j < accessibleItems.length; j++)
    System.out.print(accessibleItems[j] + " ");
   }
  }
 }
}

Read More

Creating an Exception Application in Java

Problem:

RegistrationCheck

+ registerStudent(student : Student, courseId : int) : void

Student
- id : long
- name : String
- coursesFinished : Course[]
+ Student(id : long, name : String, coursesFinished : Course[])
+ setId(id : long) : void
+ getId() : long
+ setName(name : String) : void
+ getName(): String
+ setCoursesFinished(coursesFinished : Course[]) : void
+ getCoursesFinished() : Course[]
+ toString() : String

Course
- id : int
- name : String
- preRequisite : Course
+ Course(id : int, name : String, preRequisites: Course[])
+ setId(id : int) : void
+ getId() : int
+ setName(name : String) : void
+ getName(): String
+ setPreRequisite(preRequisite: Course) : void
+ getPreRequisite() : Course
+ toString() : String



RegistrationCheckSystem
- courses : Course[]
+ registerStudent(student : Student, courseId : int) : void

RegistrationException

+ RegistrationException(message : String)

CourseNotFoundException

+ CourseNotFoundException(message : String)

In this assignment, you will be creating a Course Registration Checking System which will check if a student can register a course or not.
First, you have an interface which is the Registration interface that has one method declaration. The method is registerStudent which takes a student and a course ID as parameters.
The class Student has three private variables which are id, name, and courses finished. These variables should be initialized in the constructor and should have set and get methods.
The Course class has three private variables which are id, name, and pre-requisites. These variables should be initialized in the constructor and should have set and get methods.
The RegistrationSystem class has an array of courses and should implement the registration interface. This means that this class should implement the registerStudent method. The class has an array of available courses.
The registerStudent method should check if the student can register a specific course. The method checks if the student has finished the pre-requisites of a specific course. If so, the methods should print that the student can register this course. If the student has not completed the pre-requisites, a RegistrationException should be thrown. If the course that the student wants to register is not found, a CourseNotFoundException should be thrown.
The CourseNotFoundExceptionclass should extends the Java Exception class and call the superclass’ constructor in its constructor.
The RegistrationException class should extends the Java Exception class and call the superclass’ constructor in its constructor.
Write a tester class that creates a student and checks if a student can register a course. For simplicity, limit the number of courses to five courses.
Input should be read from the user via a scanner. First read the user id, name, and the courses he or she has finished. The number of finished courses should be two courses only.
Then read an integer which will be the course id of the course that the student wants to register. Then call resgiterStudent passing the student and the course id as a parameter.
There are a number of exceptions that should be handled in the tester class.
InpuMissmatchException might be thrown if the user enters invalid input. If so, you should tell the user that her or his input is wrong and keep requesting to enter a valid input.
The other exception is CourseNotFoundException that will be thrown if the user enters a course id that is not found. You should handle this exception by keeping on requesting from the user to enter a valid course id.
RegistrationException will be thrown if the student has not completed the prerequisites of the course. This should be handled by printing that the student cannot register this course.
Hints:
-          Use a while loop to keep requesting valid input from the user.
-          Use the following table as a course description:

id
name
preRequisite
10
CSC243
-
11
CSC245
CSC243
12
CSC310
CSC245
13
MTH201
-
14
MTH202
MTH201

Output:

Student id: 20110515
Student name: Test Student
Courses finished: 10 13
Course to register: test
Please enter a valid input!
Course to register: 12

Student has not completed the course prerequisites

Solution:

/**--------------------Course.java-----------------*/
public class Course
{
 private int id;
 private String name;
 private Course preRequisite;
 
 
 public Course(int id, String name, Course preRequisite) {
  this.id = id;
  this.name = name;
  this.preRequisite = preRequisite;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Course getPreRequisite() {
  return preRequisite;
 }
 public void setPreRequisite(Course preRequisite) {
  this.preRequisite = preRequisite;
 }
 
 public String  toString()
 {
  
 }
 
}
/**------------CourseNotFoundException.java-----------*/
public class CourseNotFoundException extends Exception
{
 public CourseNotFoundException()
 {
  super();
 }
 public CourseNotFoundException(String message)
 {
  super(message);
 }
}
/**------------RegistrationCheck.java--------------*/
public interface RegistrationCheck
{
 void registerStudent(Student student,int courseId) 
     throws RegistrationException, CourseNotFoundException;
}
/**------------RegistrationCheckSystem.java--------*/
public class RegistrationCheckSystem implements RegistrationCheck
{
 private Course[] courses;
 public void registerStudent(Student student, int courseId)
   throws RegistrationException, CourseNotFoundException {
  courses = new Course[5];
  courses[0] = new Course(10, "CSC243", null);
  courses[1] = new Course(11, "CSC245", courses[0]);
  courses[2] = new Course(12, "CSC310", courses[1]);
  courses[3] = new Course(13, "MTH201", null);
  courses[4] = new Course(14, "MTH202", courses[3]);

  int targetCourse = -1;
  boolean preRequisiteCompleted = false;
  for (int i=0;i 14) throw new CourseNotFoundException();
   coursesFinished[0] = new Course(i,null,null);
   int j = scan.nextInt();
   if (j<10 data-blogger-escaped-j="">14) throw new CourseNotFoundException();
   coursesFinished[1] = new Course(i,null,null);
   keepLooping = false;
   }
   
   catch (InputMismatchException inputMismatchException)
   {
    scan.nextLine();
    System.err.println("Exception: " + inputMismatchException);
    System.out.println("Please enter a valid input!");
   }
   
   catch(CourseNotFoundException courseNotFoundException)
   {
    System.err.println("Exception: " + courseNotFoundException);
    System.out.println("Course does not exist");
   }
     
   keepLooping = true;
   while(keepLooping)
   {
    try
    {
     System.out.print("Course to register: ");
     int courseId = scan.nextInt();
     RegistrationCheckSystem registrationCheckSystem = new RegistrationCheckSystem();
     registrationCheckSystem.registerStudent(new Student(id,name, coursesFinished),courseId);
     keepLooping =false;
    }
   
   
   catch (InputMismatchException inputMismatchException)
   {
    scan.nextLine();
    System.err.println("Exception: " + inputMismatchException);
    System.out.println("Please enter a valid input!");
   }
   
   catch(CourseNotFoundException courseNotFoundException)
   {
    System.err.println("Exception: " + courseNotFoundException);
    System.out.println("Course does not exist");
   }
   catch(RegistrationException registrationException)
   {
    System.err.println("Execption: " + registrationException);
    System.out.println("Student has not completed the course prerequisites");
   }
   }
  }
 }
}
Read More

Implementing a Market System using LinkedList in Java

Problem:

Product
- id : int
- name : String
- expYear : int
+ Product(id : int, name : String, expYear : int)
+ setId(id : int) : void
+ getId() : int
+ setName(name : String) : void
+ getName(): String
+ setExpYear(expYear : int) : void
+ getExpYear() : int

Market
- products : LinkedList<Product>
+ Market()
+ getProducts() : LinkedList<Product>
+ addProduct(Product product) : void
+ expireProducts() : void

You are asked to implement a simple market system. The system is composed of two classes which are Product and Market.
The Product class has three private variables which are id, name, and expiration year. The class’ constructor should initialize these variables and there should be setter and getter methods for them.
The Market class has one private variable which is a linked list of type Product. The constructor should initialize the linked list. There are three methods to implement in this class. The first method is getProducts which returns the linked list. The method addProduct should add the product in its parameter to the linked list. Finally, expireProducts should remove from the list the products which have an expiration year less than 2012.
Write a tester class that has a Market object and add five products using the addProducts method. After adding, print the list, then call expireProducts and print the list after removing products that have an expiration year less than 2012.


Solution:

/**-----------------------Market.java------------------*/
import java.util.LinkedList;
import java.util.ListIterator;

public class Market {
 
 private LinkedList products;
 
 public Market() {
  products = new LinkedList();
 }
 
 public LinkedList getProducts() {
  return products;
 }
 
 public void addProduct(Product product) {
  products.add(product);
 }
 
 public void expireProducts() {
  ListIterator itr = products.listIterator(0);
  
  while (itr.hasNext()) {
   Product temp = itr.next();
   
   if (temp.getExpYear() < 2012)
    itr.remove();
  }
 }
}

/*-----------------------OrderedList.java-------------*/
import java.util.LinkedList;
import java.util.ListIterator;

public class OrderedList> {
 
 private LinkedList list;
 
 public OrderedList() {
  list = new LinkedList();
 }
 
 public void addSorted(E item) {
  ListIterator itr = list.listIterator(0);
  
  while (itr.hasNext()) {
   E temp = itr.next();
   
   if (item.compareTo(temp) < 0) {
    itr.previous();
    itr.add(item);
    return;
   }
  }
  
  list.add(item);
 }
 
 public E retrieve(E item) {
  ListIterator itr = list.listIterator(0);
  
  while (itr.hasNext()) {
   E temp = itr.next();
   
   if (temp.equals(item))
    return temp;
  }
  
  return null;
 }
 
 public void delete(E item) {
  ListIterator itr = list.listIterator(0);
  
  while (itr.hasNext()) {
   E temp = itr.next();
   
   if (temp.equals(item)) {
    itr.remove();
    return;
   }
  }
 }
 
 public int search(E item) {
  ListIterator itr = list.listIterator(0);
  
  while (itr.hasNext()) {
   E temp = itr.next();
   
   if (temp.equals(item))
    return itr.previousIndex();
  }
  
  return -1;
 }
}

/**-----------------------Product.java---------------------*/
public class Product {

 private int id;
 private String name;
 private int expYear;
 
 public Product(int id, String name, int expYear) {
  this.id = id;
  this.name = name;
  this.expYear = expYear;
 }
 
 public int getId() {
  return id;
 }
 
 public void setId(int id) {
  this.id = id;
 }
 
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public int getExpYear() {
  return expYear;
 }
 
 public void setExpYear(int expYear) {
  this.expYear = expYear;
 }
 
 public String toString() {
  return "Product "+id+": "+name+" "+expYear;
 }
}
Read More

Creating a Classes Application in Java

Problem:

Smartphone
-manufacturer : String
-name : String
 -screen : Screen
 -camera : Camera
- battery : Battery)
- profit : double 
+Smartphone(manufacturer: String ,name: String, screen : Screen , camera :Camera, battery : Battery)
+ setManufacturer(manufacturer: String ):void
 + getManufacturer() : String
 + setName(name : String) : void
+ getName() : String
+ setOs(os : OS) : void
+ getOs() : OS
+ setScreen(screen : Screen) : void
 + getScreen() : Screen
+ setCamera(camera : Camera) : void
 + getCamera() : Camera
 + setBattery(battery : Battery) : void
+ getBattery() : Battery
+ setProfit(profit : double) : void
+ getProfit() : double
+ calculateTotalPrice() : double
+ toString() : String 

OS
- name : String
- version : double
- price : double 
+ OS(name : String, version : double)
+ setName(name : String) : void
 + getName() : String
+ setVersion(version : double) : void
+ getVersion() : double
 + setPrice(price : double) : void
 + getPrice() : Double
+ toString() : String  

Screen
- type : String
- width : int
- height : int
- multitouch : boolean
- price : double 
+ Screen(type : String, width : int, height : int, multitouch : boolean)
 + setType(type : String) : void + getType() : String
+ setWidth(width : int) : void
+ getWidth() : int
+ setHeight(height : int) : void
+ getHeight() : int
+ setMultiTouch(multitouch : boolean) : void
+ getMultiTouch() : Boolean
+ setPrice(price : double) : void
+ getPrice() : Double
+ toString() : String 


Camera
- megaPixels : double
- video : boolean
- videoType : String
- price : double
+ Camera(megaPixels : double, video : boolean, videoType : String)
 + setMegaPixels(megaPixels : double) : void
 + getMegaPixels() : double
 + setVideo(video : boolean) : void
 + getVideo() : boolean
+ setVideoType(videoType : boolean) : void
 + getVideoType() : String
+ setPrice(price : double) : void
+ getPrice() : Double
+ toString() : String 


Battery
- standBy : int
- talkTime : int
- price : double
+ Battery(standBy : int, talkTime : int)
+ setStandBy(standBy : int) : void
+ getStandBy() : int
+ setTalkTime(talkTime : int) : void
+ getTalkTime() : int
+ setPrice(price : double) : void
+ getPrice() : Double
+ toString() : String 

A Smartphone is usually made up from an operating system, a screen, a camera, and a battery. Each of these components are represented in a class of their own. Each of these classes has a number of variables, a constructor, and set/get methods.
The Smartphone class is made up from each of the other classes plus three variables which are the manufacturer, the name, and the profit. You are asked to implement these classes and then write a tester class which will have three smartphones and it will print their information using the toString() method.
The calculateTotalPrice() method will sum up the prices of all other components plus the profit variable and returns the sum as a double.
Printing will be done using the following format: (variables are placed between parantheses)
(manufacturer) (name)
OS: (name) (version)
 Screen: (type) (width)x(height) (Multitouch)
 Camera: (megaPixels)MP (videoType )
Battery: (standBy) Stand By, (talkTime) Talk Time
 Price: (calculateTotalPrice())

Solution:
/**---------------------Smartphone.java-------------------*/
public class Smartphone {
 
 private String  manufacturer;
 private String  name;
 private OS      os;
 private Screen  screen;
 private Camera  camera;
 private Battery battery;
 private double  profit;
 
 public Smartphone(String manufacturer, String name,
            Screen screen, Camera camera, Battery battery) {
  this.manufacturer = manufacturer;
  this.name = name;
  this.screen = screen;
  this.camera = camera;
  this.battery = battery;
 }

 public String getManufacturer() {
  return manufacturer;
 }

 public void setManufacturer(String manufacturer) {
  this.manufacturer = manufacturer;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public OS getOs() {
  return os;
 }

 public void setOs(OS os) {
  this.os = os;
 }

 public Screen getScreen() {
  return screen;
 }

 public void setScreen(Screen screen) {
  this.screen = screen;
 }

 public Camera getCamera() {
  return camera;
 }

 public void setCamera(Camera camera) {
  this.camera = camera;
 }

 public Battery getBattery() {
  return battery;
 }

 public void setBattery(Battery battery) {
  this.battery = battery;
 }

 public double getProfit() {
  return profit;
 }

 public void setProfit(double profit) {
  this.profit = profit;
 }
 
 public double calculateTotalPrice() {
  return profit + os.getPrice() + 
        screen.getPrice() + camera.getPrice() + 
                                 battery.getPrice();
 }
 
 public String toString() {
  return manufacturer+" "+name+"\n" +
               os + screen + camera + battery + "Price: " 
                           + calculateTotalPrice() + "\n";
 }
}
/**---------------------OS.java-------------------*/
public class OS {
 
 private String name;
 private double version;
 private double price;
 
 public OS(String name, double version) {
  this.name = name;
  this.version = version;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getVersion() {
  return version;
 }

 public void setVersion(double version) {
  this.version = version;
 }

 public double getPrice() {
  return price;
 }

 public void setPrice(double price) {
  this.price = price;
 }
 
 public String toString() {
  return "OS: "+name+" "+version+"\n";
 }
}
/**---------------------Screen.java-------------------*/
public class Screen {
 
 private String  type;
 private int     width;
 private int     height;
 private boolean multiTouch;
 private double  price;
 
 public Screen(String type, int width, int height, 
                                      boolean multiTouch) {
  this.type       = type;
  this.width      = width;
  this.height     = height;
  this.multiTouch = multiTouch;
 }

 public String getType() {
  return type;
 }

 public void setType(String type) {
  this.type = type;
 }

 public int getWidth() {
  return width;
 }

 public void setWidth(int width) {
  this.width = width;
 }

 public int getHeight() {
  return height;
 }

 public void setHeight(int height) {
  this.height = height;
 }

 public boolean isMultiTouch() {
  return multiTouch;
 }

 public void setMultiTouch(boolean multiTouch) {
  this.multiTouch = multiTouch;
 }

 public double getPrice() {
  return price;
 }

 public void setPrice(double price) {
  this.price = price;
 }
 
 public String toString() {
  if (multiTouch)
   return "Screen: "+type+" "+
                      width+"x"+height+" Multitouch\n";

  return "Screen: "+type+" "+width+"x"+height+"\n";
 }
}
/**---------------------Camera.java-------------------*/
public class Camera {
 
 private double  medaPixels;
 private boolean video;
 private String  videoType;
 private double  price;

 public Camera(double medaPixels, boolean video, 
                                       String videoType) {
  this.medaPixels = medaPixels;
  this.video      = video;
  this.videoType  = videoType;
 }

 public double getMedaPixels() {
  return medaPixels;
 }

 public void setMedaPixels(double medaPixels) {
  this.medaPixels = medaPixels;
 }

 public boolean isVideo() {
  return video;
 }

 public void setVideo(boolean video) {
  this.video = video;
 }

 public String getVideoType() {
  return videoType;
 }

 public void setVideoType(String videoType) {
  this.videoType = videoType;
 }

 public double getPrice() {
  return price;
 }

 public void setPrice(double price) {
  this.price = price;
 }
 
 public String toString() {
  if (video)
   return "Camera: "+medaPixels
                                +"MP "+videoType+"\n";
  
  return "Camera: "+medaPixels+"MP\n"; 
 }
}
/**---------------------Battery.java-------------------*/
public class Battery {

 private int    standBy;
 private int    talkTime;
 private double price;
 
 public Battery(int standBy, int talkTime) {
  this.standBy  = standBy;
  this.talkTime = talkTime;
 }

 public int getStandBy() {
  return standBy;
 }

 public void setStandBy(int standBy) {
  this.standBy = standBy;
 }

 public int getTalkTime() {
  return talkTime;
 }

 public void setTalkTime(int talkTime) {
  this.talkTime = talkTime;
 }

 public double getPrice() {
  return price;
 }

 public void setPrice(double price) {
  this.price = price;
 }
 
 public String toString() {
  return "Battery: "+standBy+
               " Stand By, "+talkTime+" Talk Time\n";
 }
}

/**----------------Tester.java---------------*/
public class Tester {

 public static void main(String[] args) {
  
 Battery battery1 = new Battery(10, 7);
 Camera  camera1  = new Camera(8.0, true, "1080p");
 Screen  screen1  = new Screen("Super AMOLED", 200, 300, true);
 OS      os1      = new OS("Android", 4.1);
  
 battery1.setPrice(20.0);
 camera1.setPrice(100.0);
 screen1.setPrice(200.0);
 os1.setPrice(0.0);
  
 Smartphone sp1 = new Smartphone("Samsung", "Galaxy S3", 
                                              screen1, camera1, battery1);
  
 sp1.setOs(os1);
 sp1.setProfit(200.0);
  
 Battery battery2 = new Battery(7, 4);
 Camera  camera2  = new Camera(5.0, true, "720p");
 Screen  screen2  = new Screen("Retina Display", 150, 250, true);
 OS      os2      = new OS("IOS", 5.0);
  
 battery2.setPrice(50.0);
 camera2.setPrice(100.0);
 screen2.setPrice(300.0);
 os2.setPrice(100.0);
  
 Smartphone sp2 = new Smartphone("Apple", "iPhone", 
                                           screen2, camera2, battery2);
  
 sp2.setOs(os2);
 sp2.setProfit(300.0);
  
 Battery battery3 = new Battery(10, 7);
 Camera  camera3  = new Camera(11.0, true, "1080p");
 Screen  screen3  = new Screen("HD 1080p", 200, 300, true);
 OS      os3      = new OS("Windows Mobile", 7.1);
  
 battery3.setPrice(20.0);
 camera3.setPrice(100.0);
 screen3.setPrice(200.0);
  os3.setPrice(0.0);
  
 Smartphone sp3 = new Smartphone("Nokia", "Lumia", 
                                              screen3, camera3, battery3);
  
 sp3.setOs(os3);
 sp3.setProfit(250.0);
 
 System.out.println(sp1);
 System.out.println(sp2);
 System.out.println(sp3);
 }
}
Read More

Creating a Inheritance and Polymorphism Application in Java

Problem:

Vehicle
- manufacturer : String
- name : String
- engine : Engine
 - body : Body
- profit : double
+ Vehicle(manufacturer : String, name : String, engine : Engine, body : Body, profit : double) 
+ setManufacturer(manufacturer : String) : void
+ getManufacturer() : String
 + setName(name : String) : void
 + getName() : String
 + setEngine(engine : Engine) : void
+ getEngine() : Engine
+ setBody(body : Body) : void
+ getBody() : body
+ setProfit(profit : double) : void
 + getProfit() : double
 # abstract calculateTatalPrice() : double
+ toString() : String


Car
- doors : int
- gear : String
 - gearPrice : double
+ Car(manufacturer : String, name : String, engine : Engine, body : Body, profit : double, doors : int, gear : String, gearPrice : double)
+ setDoors(doors : int) : void
+ getDoors() : int
 + setGear(gear : String) : void
 + getGear() : String
+ setGearPrice(gearPrice : double) : void
 + getGearPrice() : double
+ calculateTotalPrice() : double
+ toString() : String     


Train
- compartments : int
- fuel : String
- cornpartmentPrice : double
+ Train(manufacturer : Stricw, name : String, engine : Engine, body : Body, profit : double, compartments : int, fuel : String, compartmentPrice : double)
+ setCompartments (compartments : int) : void
+ getCompartments () : int
+ setFuel(fuel : String) : void
 + getFuel() : String
 + setCompartmentPrice(compartmentPrice : double) : void
+ getCompartmentPrice () : double + calculateTotalPrice() : double
+ toString() : String


Engine
- id : String
- cost : double 
+ Engine(id : String, cost : double)
+ setld(id : String) : void
+ getld() : String
+ setCost(cost : double) : void
 + getCost() : double
 + toString() : String


Body
- width :
- height : double
- seats : int
 - cost : double
+ Body(width : double, height : double, seats: int, cost : double)
+ setWidth(width : double) : void
+ getWidth() : double
 + setHeight(height : double) : void
+ getHeight() : double
 + setSeats(seats : int) : void
+ getSeats() : int
+ setCost(cost : double) : void
+ getCost() : double
+ toString() : String

In this lab, you will be using inheritance to create a car and a train.
The Vehicle class is made up of an Engine and a Body and some other variables. It has setter and getter methods and a method called calculateTotalPrice which should be implemented by subclasses of Vehicle.
The Car class and the Train class are both subclasses of Vehicle. This means that you have to use inheritance to create both classes. Each of these classes' constructors must call the superclass constructor. Moreover, both of these classes have to implement the calculateTotalPrice method which has to sum up the total price of the vehicle plus the compartments' price if it is a train or the gear price if it is a car.
Write a tester class which has an array of Vehicles.
The array should contain two cars and two trains.
 Printing format is as follows:
(manufacturer) (name)
Engine:
(id) $(cost)

Body:
 (width)x(height)M
 (seats) seats
 (compartments) compartments (if train)
(doors) doors (if car)

Price:
 $(calculateTotalPrice())

Solution:
/**-----------------------Vehicle.java-------------------*/
public abstract class Vehicle {
 
 private String manufacturer;
 private String name;
 private Engine engine;
 private Body   body;
 private double profit;
 
 public Vehicle(String manufacturer, String name, 
                  Engine engine, Body body, double profit) {
  this.manufacturer = manufacturer;
  this.name         = name;
  this.engine       = engine;
  this.body         = body;
  this.profit       = profit;
 }

 public String getManufacturer() {
  return manufacturer;
 }

 public void setManufacturer(String manufacturer) {
  this.manufacturer = manufacturer;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Engine getEngine() {
  return engine;
 }

 public void setEngine(Engine engine) {
  this.engine = engine;
 }

 public Body getBody() {
  return body;
 }

 public void setBody(Body body) {
  this.body = body;
 }

 public double getProfit() {
  return profit;
 }

 public void setProfit(double profit) {
  this.profit = profit;
 }
 
 protected abstract double calculateTotalPrice();
 
 public String toString() {
  return manufacturer + " " + name + 
                     "\n\nEngine:\n" + engine.getId() + 
                   " $" + engine.getCost() + "\n\nBody:\n" + 
                    body.getWidth() + "x" + body.getHeight() +
                        "M\n" + body.getSeats() + " seats\n";
 }
}

/**-----------------------Car.java-------------------*/
public class Car extends Vehicle {

 private int    doors;
 private String gear;
 private double gearPrice;
 
 public Car(String manufacturer, String name, Engine engine,
                  Body body, double profit, int doors, String gear, 
                                                 double gearPrice) {
  super(manufacturer, name, engine, body, profit);
  this.doors     = doors;
  this.gear      = gear;
  this.gearPrice = gearPrice;
 }

 public int getDoors() {
  return doors;
 }

 public void setDoors(int doors) {
  this.doors = doors;
 }

 public String getGear() {
  return gear;
 }

 public void setGear(String gear) {
  this.gear = gear;
 }

 public double getGearPrice() {
  return gearPrice;
 }

 public void setGearPrice(double gearPrice) {
  this.gearPrice = gearPrice;
 }

 @Override
 protected double calculateTotalPrice() {
  return getEngine().getCost() + 
                   getBody().getCost() + getProfit() + gearPrice;
 }
 
 public String toString() {
  return super.toString() + doors 
         + " doors\n\nPrice:\n$" + calculateTotalPrice() + "\n\n";
 }
}
/**-----------------------Train.java-------------------*/
public class Train extends Vehicle {

 private int    compartments;
 private String fuel;
 private double compartmentPrice;
 
 public Train(String manufacturer, String name, Engine engine,
                 Body body, double profit, int compartments, 
                            String fuel, double compartmentPrice) {
  super(manufacturer, name, engine, body, profit);
  this.compartments = compartments;
  this.fuel = fuel;
  this.compartmentPrice = compartmentPrice;
 }

 public int getCompartments() {
  return compartments;
 }

 public void setCompartments(int compartments) {
  this.compartments = compartments;
 }

 public String getFuel() {
  return fuel;
 }

 public void setFuel(String fuel) {
  this.fuel = fuel;
 }

 public double getCompartmentPrice() {
  return compartmentPrice;
 }

 public void setCompartmentPrice(double compartmentPrice) {
  this.compartmentPrice = compartmentPrice;
 }

 @Override
 protected double calculateTotalPrice() {
  return getEngine().getCost() + getBody().getCost() 
                    + getProfit() + (compartments*compartmentPrice);
 }

 public String toString() {
  return super.toString() + compartments + 
        " compartments\n\nPrice:\n$" + calculateTotalPrice() + "\n\n";
 }
}

/**-----------------------Engine.java-------------------*/
public class Engine {
 
 private String id;
 private double cost;
 
 public Engine(String id, double cost) {
  this.id   = id;
  this.cost = cost;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public double getCost() {
  return cost;
 }

 public void setCost(double cost) {
  this.cost = cost;
 }
 
 public String toString() {
  return "";
 }
}
/**-----------------------Body.java-------------------*/
public class Body {
 
 private double width;
 private double height;
 private int    seats;
 private double cost;
 
 public Body(double width, double height,
                                   int seats, double cost) {
  this.width  = width;
  this.height = height;
  this.seats  = seats;
  this.cost   = cost;
 }

 public double getWidth() {
  return width;
 }

 public void setWidth(double width) {
  this.width = width;
 }

 public double getHeight() {
  return height;
 }

 public void setHeight(double height) {
  this.height = height;
 }

 public int getSeats() {
  return seats;
 }

 public void setSeats(int seats) {
  this.seats = seats;
 }

 public double getCost() {
  return cost;
 }

 public void setCost(double cost) {
  this.cost = cost;
 }
 
 public String toString() {
  return "Body:\n" + width + "x" + 
                             height + "M " + seats + " seats\n\n";
 }
}
/**-----------------------Tester.java-------------------*/
public class Tester {
 
 public static void main(String args[]) {
  
  Engine engine1 = new Engine("150511", 2000);
  Engine engine2 = new Engine("151211", 3000);
  Engine engine3 = new Engine("150911", 4000);
  Engine engine4 = new Engine("151515", 5000);
  
  Body body1 = new Body(2.3, 1.2, 2, 2000);
  Body body2 = new Body(2.6, 1.5, 4, 3000);
  Body body3 = new Body(20.3, 3.2, 50, 4000);
  Body body4 = new Body(30.3, 3.2, 70, 5000);
  
  Vehicle vehicles[] = new Vehicle[4];
  
  vehicles[0] = new Car("Company1", "Car1", 
                    engine1, body1, 10000, 2, "Manual", 500);
  vehicles[1] = new Car("Company2", "Car2", 
                    engine2, body2, 20000, 4, "Automatic", 400);
  vehicles[2] = new Train("Company1", "Train1", 
                    engine3, body3, 50000, 10, "Coal", 200);
  vehicles[3] = new Train("Company2", "Train2", 
                    engine4, body4, 100000, 20, "Electricity", 300);
  
  for (int i = 0; i < vehicles.length; i++) {
   if (vehicles[i] instanceof Train) {
    
    Train currentVehice = (Train) vehicles[i];
    System.out.println(currentVehice.toString());
    
   } else {
    
    Car currentVehice = (Car) vehicles[i];
    System.out.println(currentVehice.toString());
    
   }
  }
 }
}

Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact