Question

In: Computer Science

java programming Create a class named Money. It should have member variables for Member Variables Store...

java programming

Create a class named Money. It should have member variables for
Member Variables
Store dollars and cents as members (both should be int). They should be
accessible from only inside the class.
Methods
 Write a default constructor that sets members to 0.
 Write a two-parameter constructor that sets members to the parameter
values.
 Write get/set methods for the member variables.

 Write an override method for toString. The returned string should be
formatted as a normal money string. For example, if dollars is 2 and cents is
5 then it should return $2.05. If dollars is 3 and cents is 50 then it should
return $3.50.
 Write an override method for equals. It should return true if both the
dollars and cents are equal and false otherwise. This means you compare
the dollars in the current to the dollars in the other and you compare the
cents in one to the cents in another.

Class – Main
The main method should be in this class.
 Declare an array of Money in main. The array should have 20 elements.
 Populate the array with data from a file. Use a loop to read data from the
input file. Use the input file data given at the end of this document.
 Write a loop that will print all elements of the array on screen. You should
have read all data from the input file before doing this.
 Write a loop that will add up all the money in the array and store the total
in another Money instance. After the loop print the total money on screen
using the Money instance that has the total. You should use toString to get
the formatted money string. The total money that gets print should not
have a cents value over 99. For example, 7 dollars and 160 cents should be
8 dollars and 60 cents. You should have read all data from the input file
before doing this.
 Add two calls to the Money equals override. One to demonstrate that the
instances are equal and another to demonstrate that they are not equal.

Solutions

Expert Solution

// Money.java

public class Money {
  
   // fields
   private int dollars;
   private int cents;
  
   // default constructor to set dollars and cents to 0
   public Money()
   {
       this(0,0);
   }
  
   // parameterized constructor to set the dollars cents to input values
   public Money(int dollars, int cents)
   {
       // validate dollars >=0 , else set it to 0
       if(dollars >= 0)
           this.dollars = dollars;
       else
           this.dollars = 0;
      
       // validate cents >=0 , else set it to 0
       if(cents >= 0 )
           this.cents = cents;
       else
           this.cents = 0;
      
       // loop to convert to cents to [0,99] in case it is >= 100
       while(this.cents > 99)
       {
           this.cents -= 100;
           this.dollars++;
       }
   }

   // method to return the dollars
   public int getDollars()
   {
       return dollars;
   }
  
   // method to return the cents
   public int getCents()
   {
       return cents;
   }
  
   // method to set the dollars
   public void setDollars(int dollars)
   {
       // validate dollars >=0, else don't update
       if(dollars >=0 )
           this.dollars = dollars;
   }
  
   // method to set the cents
   public void setCents(int cents)
   {
       // validate cents >=0, else don't update
       if(cents >= 0)
           this.cents = cents;

       // loop to convert to cents to [0,99] in case it is >= 100
       while(this.cents > 99)
       {
           this.cents -= 100;
           this.dollars++;
       }
   }
  
   // method to return String representation of the Money
   public String toString()
   {
       return String.format("$%d.%02d",dollars,cents );
   }
  
   // method to return true if this and obj are equal else return false
   public boolean equals(Object obj)
   {
       // validate obj is an object of Money
       if(obj instanceof Money)
       {
           Money other = (Money)obj; // cast obj to Money
          
           // two Money objects are equal only if both dollars and cents are equal
           return dollars == other.dollars && cents == other.cents;
       }
      
       return false;
   }
}

//end of Money.java

// Main.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
  
   public static void main(String[] args) throws FileNotFoundException {

       int size = 0;
       int dollars, cents;
      
       // create an array of 20 Money objects
       Money[] money = new Money[20];
      
       // create the File object for the input file
       File file = new File("moneyInput.txt");
       // open the input file
       Scanner fileScan = new Scanner(file);
         
       // loop to read dollars and cents from input file till the end of file or till 20 object data are read
       while((fileScan.hasNext()) && (size < money.length))
       {
           dollars = fileScan.nextInt();
           cents = fileScan.nextInt();
          
           money[size] = new Money(dollars,cents);
           size++;
       }
      
       fileScan.close(); // close the file
      
       // create an object to contain sum of all money objects
       Money totalMoney = new Money();
      
       // loop to display each Money object and calculate sum of all money objects
       for(int i=0;i<size;i++)
       {
           System.out.println("Money "+(i+1)+": "+money[i]);
           totalMoney.setDollars(totalMoney.getDollars()+money[i].getDollars());
           totalMoney.setCents(totalMoney.getCents()+money[i].getCents());
       }
      
       // display the total money
       System.out.println("Total Money: "+totalMoney);
      
       // test the equals method
       Money m1 = new Money(12,50);
       Money m2 = new Money(12,50);
       Money m3 = new Money(10,50);
      
       System.out.println(m1+" == "+m2+": "+(m1.equals(m2)));
       System.out.println(m1+" == "+m3+": "+(m1.equals(m3)));
   }

}

// end of Main.java

Output:

Input file: moneyInput.txt (Each line of the file contains 2 integers representing dollar and cent)

Output:


Related Solutions

JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
First lab: Create a Fraction class Create member variables to store numerator denominator no additional member...
First lab: Create a Fraction class Create member variables to store numerator denominator no additional member variable are allowed Create accessor and mutator functions to set/return numerator denominator Create a function to set a fraction Create a function to return a fraction as a string ( common name ToString(), toString())  in the following format: 2 3/4 use to_string() function from string class to convert a number to a string; example return to_string(35)+ to_string (75) ; returns 3575 as a string Create...
(java) Write a class called CoinFlip. The class should have two instance variables: an int named...
(java) Write a class called CoinFlip. The class should have two instance variables: an int named coin and an object of the class Random called r. Coin will have a value of 0 or 1 (corresponding to heads or tails respectively). The constructor should take a single parameter, an int that indicates whether the coin is currently heads (0) or tails (1). There is no need to error check the input. The constructor should initialize the coin instance variable to...
THIS IS JAVA PROGRAMMING 1. Create a class named Name that contains the following: • A...
THIS IS JAVA PROGRAMMING 1. Create a class named Name that contains the following: • A private String to represent the first name. • A private String to represent the last name. • A public constructor that accepts two values and assigns them to the above properties. • Public methods named getProperty (e.g. getFirstName) to return the value of the property. • Public methods named setProperty ( e.g. setFirstName)to assign values to each property by using a single argument passed...
Java Programming Create a class named Problem1, and create a main method, the program does the...
Java Programming Create a class named Problem1, and create a main method, the program does the following: - Prompt the user to enter a String named str. - Prompt the user to enter a character named ch. - The program finds the index of the first occurrence of the character ch in str and print it in the format shown below. - If the character ch is found in more than one index in the String str, the program prints...
Using C++ programming. Thank you. Money class has the following member variables and functions. -member variable...
Using C++ programming. Thank you. Money class has the following member variables and functions. -member variable : dollar, cent -member function : setMoney(int dollar, int cent), printMoney(), operator overloading(+) Program the Money class so that the following function can be performed. int main(){ Money a, b, c; A.setMoney(10, 60); B.setMoney(20, 70; (a+b).printMoney(); c = a + b; c.printMoney(); }
1. Create a1. Create a new java file named Name.java that should have Name class based...
1. Create a1. Create a new java file named Name.java that should have Name class based on new java file named Name.java that should have Name class based on the following UML Name - first: String - last: String + Name () + Name (String firstName, String lastName) + getName () : String + setName (String firstName, String lastName) : void + getFirst () : String + setFirst (String firstName) : void + getLast () : String + setLast (String...
In java: -Create a class named Animal
In java: -Create a class named Animal
java True or False. no need to explain 6. Class member variables should be declared as...
java True or False. no need to explain 6. Class member variables should be declared as private because the objectoriented programming principle of encapsulation. 7. The method public char getChar(); will return a character data. Page 2 8. Assume that there is a Class named Stock and the class has a constructor private Stock(String symbol, double price); So a programmer can create a Stock object by doing the following in the main method: Stock stock = new Stock(“Google Inc”, 578.45);...
Java- Create a new class named Forest that has a 2D array of integers to store...
Java- Create a new class named Forest that has a 2D array of integers to store a forest. Create a private inner class Position to store the row and column of the current cell. Create a Depth First Search Method that uses a stack to remove the current tree and search its neighbors based on the following pseudocode: // given a forest "f" // store positions on fire Stack<Position> cellsToExplore // the forest is aflame! for each tree in the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT