/* To do: * - Allow user to use the below functions to add name and coin...
Fantastic news! We've Found the answer you've been seeking!
Question:
/* To do: * - Allow user to use the below functions to add name and coin to populate the array addItemToArray(); * - Checks array for same name and updates coin value test2.addCoin()
* * Current errors: * - Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "test1.coin" is null */
test1
import java.util.Scanner; public class test1 { private static test2[] coin; public static void main(String[] args) { addToArray(); addItemToArray(); } private static void addToArray() { test2[] coin2 = new test2[coin.length + 1]; System.arraycopy(coin, 0, coin2, 0, 0); coin = coin2; } private static void addItemToArray() { Scanner input = new Scanner(System.in); test2[] coin = new test2[0]; while(true) { System.out.println("Add user? 1. Yes 2. No"); int choice = input.nextInt(); if(choice == 1) { for(int i = 0; i <= coin.length; i++) { System.out.println("Enter name: "); String name = input.nextLine(); System.out.println("Enter change: "); int cash = input.nextInt(); // checks for existing user and updates for(int j = 0; j < coin.length; j++) { if(coin[j].getName().equals(name)) { test2 change = new test2(); test2.addCoin(cash); coin[j] = change; break; } } addToArray(); coin[i].setName(name); coin[i].setCoin(cash); System.out.println("Add more? 1. Yes 2. No"); choice = input.nextInt(); if(choice == 2) { break; } } }if(choice == 2){ break; } } } }
test2
public class test2 { private String name; private int coin; public test2() { this.name = "no name"; this.coin = 0; } public test2(String name, int coin) { this.name = name; this.coin = coin; } public void addCoin(int cash) { this.coin +=cash; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCoin() { return coin; } public void setCoin(int coin) { this.coin = coin; } }
Related Book For
Java An Introduction To Problem Solving And Programming
ISBN: 9780134462035
8th Edition
Authors: Walter Savitch
Posted Date: