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

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...
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:)
Declare a string variable and initialize it with your first name ( in C++)
Declare a string variable and initialize it with your first name ( in C++)
Create a class DogWalker member List <String>doggies method: void addDog(String name ) //add dog to the...
Create a class DogWalker member List <String>doggies method: void addDog(String name ) //add dog to the List method: void printDogList() //print all dogs in list /* You’ll need an index. Iterate over your list of dog names in a while loop. Use your index to “get” the dog at the current index When you ‘find’ your dog name in the list, print it out */ Method: void findDogUsingWhile(String dogName) /* You’ll need an index. Iterate over your list of dog...
A study was done on protected and non protected tests. The results are shown in the...
A study was done on protected and non protected tests. The results are shown in the table. Assume that the two samples are independent simple random samples selected from normally distributed​ populations, and do not assume that the population standard deviations are equal. Complete parts​ (a) and​ (b) below. Use a 0.01 significance level for both parts. Protected Non-protected μ μ 1 μ 2 n 30 34 x̅ 77.53 81.35 s 10.06 18.26 b. Construct a confidence interval suitable for...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT