Question

In: Computer Science

protected String name;                                      &nbsp

protected String name;                                                                                                          
protected ArrayList<Stock> stocks;    
protected double balance;                                                                             
+ Account ( String name, double balance) //stocks = new ArrayList<Stock>() ;
+ get and set property for name; get method for balance
+ void buyStock(String symbol, int shares, double unitPrice )
//update corresponding balance and stocks ( stocks.add(new Stock(…..)); )
+ deposit(double amount) : double //returns new balance                                                                
+ withdraw(double amount) : double //returns new balance
+ toString() : String                                                             

    @Override
    public String toString(){
        StringBuffer str = new StringBuffer("Stocks: ");
        for (Stock s : stocks){
            str.append(s.toString() + " ");
        }
        return "Name: " + name + ", balance: " + balance +"\t" + str.toString();
    }

can anyone convert this to java?

Solutions

Expert Solution

I have implemented the given model to the Java class. First let me write the complete code here.

Code:

import java.util.ArrayList;

class Stock
{
protected String symbol;
  
protected int shares;
  
protected double unitPrice;
  
Stock(String symbol, int shares, double unitPrice)
{
this.symbol = symbol;
  
this.shares = shares;
  
this.unitPrice = unitPrice;
}
}   

public class Account
{
protected String name;
  
protected ArrayList<Stock> stocks;
  
protected double balance;
  
Account(String name, double balance)
{
this.name = name;
  
stocks = new ArrayList<Stock>();
  
this.balance = balance;
}

public String getName() {
return name;
}

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

public double getBalance() {
return balance;
}

void buyStock(String symbol, int shares, double unitPrice )
{

balance = balance - shares*unitPrice;

stocks.add(new Stock(symbol, shares, unitPrice));
}
  
public double deposit(double amount)
{
balance = balance + amount;
  
return balance;
}
  
public double withdraw(double amount)
{
balance = balance - amount;
  
return balance;
}
  
@Override
public String toString(){
StringBuffer str = new StringBuffer("Stocks: ");
for (Stock s : stocks){
str.append(s.toString() + " ");
}
return "Name: " + name + ", balance: " + balance +"\t" + str.toString();
}
}

Explanation:

Here, + indicates they are public methods. Account is a public method that indicates it is a constructor. So, the class name must be Account. This class has 3 protected variables as given here. So I added them along with the required get and set methods.

Then comes buyStocks() method. Here, it is mentioned that stock is added in the arrayList of type Stock so 'Stock' must be a class. So, I created a Stock class definition as per the details i could extract from given data. It will have 3 protected variables and a parameterized constructor. This constructor is called in buyStocks() so I have written the same as mentioned in the question.

It has also mentioned to update the balance. So, I thought for the same and concluded that if I am buying the stock in my account, then the account will be added with that stock but the balance will get deducted that was used to purchase the stock. So, to find the balance used to buy the stocks: multiply unit share price with number of shares. This will give me amount I spent for that stock and I am subtracting it from balance.

deposit() method is having return type double. It gives amount which was credited so we need to add that amount in the balance so that we get new balance and after that the new balance is returned by this method.

withdraw() method is also having return type double. It gives amount to be deducted from balance. So, we subtracted it from balance and got the new balance which is returned by the method.

The toString() method implementation is already given here. You do not need to change single line in it. So, the complete code and the explanation is this.

Do comment if there is any query. I will solve it for sure. Thank you. :)


Related Solutions

Base Class class TransportationLink { protected: string _name; double _distance; public: TransportationLink(const string &name, double distance);...
Base Class class TransportationLink { protected: string _name; double _distance; public: TransportationLink(const string &name, double distance); const string & getName() const; double getDistance() const; void setDistance(double); // Passes in the departure time (as minute) and returns arrival time (as minute) // For example: // 8 am will be passed in as 480 minutes (8 * 60) // 2:30 pm will be passed in as 870 minutes (14.5 * 60) virtual unsigned computeArrivalTime(unsigned minute) const = 0; }; #endif Derived Classes...
Java public class UpperCaseString { //1      protected String content; // 2      public UpperCaseString(String content)...
Java public class UpperCaseString { //1      protected String content; // 2      public UpperCaseString(String content) { // 3           this.content = content.toUpperCase(); // 4      } // 5      public String toString() { // 6           return content.toUpperCase(); // 7      } // 8      public static void main(String[] args) { // 9           UpperCaseString upperString =              new UpperCaseString("Hello, Cleo!"); // 10           System.out.println(upperString); // 11      } // 12 } // 13 THE FOLLOWING 3 QUESTIONS REFER...
PREVIOUS CODE: InventroryItems class InventoryItem implements Cloneable{ // instance variables protected String description; protected double price;...
PREVIOUS CODE: InventroryItems class InventoryItem implements Cloneable{ // instance variables protected String description; protected double price; protected int howMany; // constructor public InventoryItem(String description, double price, int howMany) { this.description = description; this.price = price; this.howMany = howMany; } // copy constructor public InventoryItem(InventoryItem obj) { this.description = obj.description; this.price = obj.price; howMany = 1; } // clone method @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } // toString method @Override public String toString() { return description +...
In Java, Here is a basic Name class. class Name { private String first; private String...
In Java, Here is a basic Name class. class Name { private String first; private String last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Name other) { return this.first.equals(other.first) && this.last.equals(other.last); } } Assume we have a program (in another file) that uses this class. As part of the program, we need to write a method with the following header: public static boolean exists(Name[] names, int numNames, Name name) The goal of...
public class Person { private String name; public Person() { name = "No name yet"; }...
public class Person { private String name; public Person() { name = "No name yet"; } public Person(String initialName) { name = initialName; } public void setName(String newName) { name = newName; } public String getName() { return name; } public void writeOutput() { System.out.println("Name: " + name); } public boolean hasSameName(Person otherPerson) { return this.name.equalsIgnoreCase(otherPerson.name); } } 2- Write a Program Patient. Java Class that extends Person to include  Social security Gender  Appropriate construtors, accessors, and mutators....
Part 1 readFile(String filename) In this method you are passed a String with the name of...
Part 1 readFile(String filename) In this method you are passed a String with the name of a file. This method will read the file in line by line and store each line in a String array. This String array is then returned. An example is shown below. File Contents: Purple Rain by Prince I never meant to cause you any sorrow I never meant to cause you any pain I only wanted one time to see you laughing I only...
A constructor, with a String parameter representing the name of the item.
USE JAVA Item classA constructor, with a String parameter representing the name of the item.A name() method and a toString() method, both of which are identical and which return the name of the item.BadAmountException ClassIt must be a RuntimeException. A RuntimeException is a subclass of Exception which has the special property that we wouldn't need to declare it if we need to use it.Inventory classA constructor which takes a String parameter indicating the item type, an int parameter indicating the initial...
Write a class called Account that contains: • Three privateinstance variables: name (String), account (String),...
Write a class called Account that contains: • Three private instance variables: name (String), account (String), account balance (double). • One constructor, which constructs all instances with the values given. • Getters and setters for all the instance variables. • Debit function that takes an amount from the user and subtract the balance (make sure the balance will not drop below zero after the operation, if this was the case, the function should return false else it should return true)...
Function 6: Sorting string function name (str) a. This function receives an string. Your task is...
Function 6: Sorting string function name (str) a. This function receives an string. Your task is loop through the each character of the string and separate all digists/letters/special characters. Display all digits at the beginning, followed by letters then the special chars and display result in console. For example if following string is passed to this function “ha1m2i3:n)” Result should be: 123hamin:)
Implement function get_contact(contacts, name) that returns a string. The contacts and the name parameter are both...
Implement function get_contact(contacts, name) that returns a string. The contacts and the name parameter are both type string. This function checks for the name string in the contacts string and returns that person’s contact information. If the person is not found, the function returns, “name not in contact”. Assume input is always valid. Assume the same name is not repeated in contacts. [You may use split(), range(), len() ONLY and no other built-in function or method] Examples:               contacts = “Frank...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT