Although your focus is in creating an instance Finance
there are few concepts I'd like to invite you to explore.
To start and to answer your question, the Finance
's contructor signature defines the contract for a Finance
oject to become an instance.
It expects two arguments, each of which are of ArrayList
type.
To create an instance of Finance
you have to create two arrays, one made of Strings and the other made of Doubles, on this thread you have many ideas on how to initialise arrays.
An example could be,
new Finance(new ArrayList<>(List.of("Movies")), new ArrayList<>(List.of(1.0)));
Next, I'd like to drag your awareness on this expression in your code:
title.add("Movies")
title
is what you want initialised inside your constructor and altough is not a bad idea to have it initialised as an empty ArrayList as you did, it's pointless to add an element to it and then pass it to your constructor for it to change the same instance object.
Next, I'd like to drag your awareness on the types you are using:
In my personal opinion I would use java's List
interface when declaring variables, use a plural to name any collection of objects, and in your case, use ArrayList
as the List
interface implementing class. For example,
List<String> titles;
// and
List<Double> expenses;
Same on the constructor:
public Finance(List<String> titles, List<Double> expenses) {
//...init variables here
}
Note that I renamed moneySpent
to expenses
. I did this because a money spent on multiple moments it's more likely to be expenses and moneySpent
would be the amount spent on a single moment.
Applying Single Resposibility I would refactor the creation of a Finance
instance onto a separete (static, why static?) method.
public class Finance {
List<String> titles;
List<Double> expenses;
Scanner input = new Scanner(System.in);
public Finance(List<String> titles, List<Double> expenses) {
this.titles = titles;
this.expenses = expenses;
System.out.println(this.titles);
System.out.println(this.expenses);
}
public static void main(String[] args) {
Finance entertainment = createFinance();
}
private static Finance createFinance() {
return new Finance(
new ArrayList<>(List.of("Movies")),
new ArrayList<>(List.of(1.0)));
}
}
Lastly, Consider driving your implementation guided by tests. I can recommend:
TDD by example, GOOS and Jason Gorman's TDD book