Hey guys. I'm trying to make a class called "purse" where I make an array list and store String in it (quarters, dimes, etc), and then I print out the names of each coin I stored in the purse. I got the printing out part just fine. Then I have to make a method where I reverse the order of the names and prints them out as well. I think I got this one right until I print them out and notice that I get an error in the output. This is the "reverse" method. Could anyone tell me what I'm doing wrong here?
import java.util.ArrayList; public class Purse { private ArrayList<String> coins; private ArrayList<String> reverseArray; public Purse() { ArrayList<String> coin = new ArrayList<String>(); coins = coin; } public void addCoin(String coinName) { coins.add(coinName); } public String reverse() { int n = coins.size(); for(int i = n; i == 0; i--) { String s = coins.get(n); reverseArray.add(s); } String reverseWords = reverseArray.toString(); return reverseWords; } public String toString() { String words = coins.toString(); return words; } }
public class PurseTester { public static void main(String[] args) { Purse jean = new Purse(); jean.addCoin("Quarter"); jean.addCoin("Dime"); jean.addCoin("Nickel"); jean.addCoin("Dime"); System.out.println(jean.toString()); System.out.println(jean.reverse()); } }
Output:
[Quarter, Dime, Nickel, Dime]
Exception in thread "main" java.lang.NullPointerException
at Purse.reverse(Purse.java:27)
at PurseTester.main(PurseTester.java:12)