Skip to content
Advertisement

Why isn’t my Array updating outside of the method that it is set in after I assign it a new value?

I have an issue where when I combine two arrays ‘laptops’ and ‘arr2’ in the addLaptop() method and create a third array ‘newArray’ to contain the values of ‘laptops’ and ‘arr2’ then set the ‘laptops’ array equal to the value of ‘newArray’ and print ‘laptops’ within my addLaptop() method the value of ‘laptops’ will be equal ‘newArray’ just like I want.

However, when I try grabbing the data out of the ‘laptops’ from my printAllLaptops() method the values in the ‘laptops’ array are set back to their original values instead of being set to the values of ‘newArray’ like I want them to be.

What is my problem here I can’t figure out why the values won’t update? I have been stuck on this issue for hours now and have tried moving the ‘laptops’ array around into my different methods and have tried setting laptops = newArray and have also tried returning laptops a few different ways from my addLaptop() method.

Code That Calls My Methods: LaptopFinderApp.java

package docComments;

import java.util.Scanner;

public class LaptopFinderApp {
    
    public static void main(String[] args) {
        
        int loop = 0;
        
        while (loop !=1) {
            String userInput = null;
            
                // Entering 1 is what calls the method I am having issues with
                System.out.println("1. Show all laptops");
                // Entering 2 is what calls the method that updates my 'laptops Array'
                System.out.println("2. Add a laptop");
                System.out.println("3. Find a laptop");
                System.out.println("4. Delete a laptop");
                System.out.println("5. Number of laptops");
                System.out.println("6. Exit");
                System.out.println("Enter your selection:" );
                Scanner myObj = new Scanner(System.in);
                userInput = myObj.nextLine();  // Read user input
                System.out.println();
    
                
                // Converts user input from a string to an integer
                int convertedInput = Integer.parseInt(userInput);
                
                // Handels user inputs
                if (convertedInput > 6) {
                    System.out.println("Enter a selection 1 - 6");
                } else if (convertedInput == 6) {
                    System.out.println("Goodbye");
                    break;
                } else if (convertedInput == 5) {
                    
                } else if (convertedInput == 4) {
                    
                } else if (convertedInput == 3) {
                    
                } else if (convertedInput == 2) {
                    System.out.println("GPU:");
                    String cpu = myObj.nextLine();
                    System.out.println("CPU:");
                    String gpu = myObj.nextLine();
                    System.out.println("Battery Life:");
                    String batterylife = myObj.nextLine();
                    
                    Laptops addLaptop = new Laptops(gpu, cpu, batterylife);
                    addLaptop.addLaptop();
                    
                } else if (convertedInput == 1) {
                    
                    Laptops name = new Laptops(null, null, null);
                    name.printAllLaptops();
                    
                } else if (convertedInput < 1) {
                    System.out.println("Enter a selection 1 - 6");
                } else {
                    System.out.println("Error please try again.");
                }
                System.out.println();
        }
    }
}

My Code That is The Issue: Laptops.java

package docComments;

import java.util.Arrays;

public class Laptops {
    /**
     * Needs to have GPU, CPU, Battery Life, unique id and static count as attributes.
     */
    private String gpu;
    private String cpu;
    private String batterylife;
    private int id;
    private int counter;
    
        public Laptops(String gpu, String cpu, String batterylife) {
                this.gpu =  gpu;
                this.cpu = cpu;
                this.batterylife = batterylife;
                this.id = 1000003;
        }
        
        
        /**
         * Returns the GPU of the Laptop.
         * @return the GPU
         */
        public String getGpu() {
            return gpu;
        }

        /**
         * Returns the CPU of the Laptop.
         * @return the CPU
         */
        public String getCpu() {
            return cpu;
        }

        /**
         * Returns the batterylife of the Laptop.
         * @return the batterylife
         */
        public String getBatteryLife() {
            return batterylife;
        }
        
        /**
         * Returns the user inputed id of the Laptop.
         * @return the user inputed id
         */
        public int getId() {
            return id;
        }
        
        
        /**
         * Returns the new id we created.
         * @return the new id
         */
        public int creatId() {
            counter = counter + 1;
            id = id + counter;
            return id;
        }
        
        
        /**
         * Array of laptops
         */
        String[][] laptops = {
                {"1000001", "RTX 3080", "Intel i7", "24h"},
                {"1000002", "RTX 4090", "Intel i9", "16h"},
                {"1000003", "GTX 1660", "Ryzen 5", "34h"}
        };
        
        
        /**
         * Prints all of the laptops in our array
         */
        public void printAllLaptops() {
            System.out.println(Arrays.toString(laptops)); // only displays the three original laptops
             for (int i = 0; i < laptops.length; ++i) {
                 System.out.println("Laptop " + i +": " + "ID:" + laptops[i][0] + " " + laptops[i][1] + " " + laptops[i][2] + " " + laptops[i][3]);
             }
        }
        
        /**
         * Adds user created laptop to laptops array
         */
        public String[][] addLaptop() {
            if (gpu != null) {
            String arr2[][] = {{String.valueOf(creatId()), gpu, cpu, batterylife}};
            
            // create new array 
            String newArray[][] = new String[laptops.length + arr2.length][];
            
            // Copy laptops array to new array from 0 to laptops.length
            System.arraycopy(laptops, 0, newArray, 0, laptops.length);
            
            // copy second array to new array
            System.arraycopy(arr2, 0, newArray, laptops.length, arr2.length);
                        
            // display all arrays
            System.out.println("Array1 = " + Arrays.toString(laptops[0]));
            System.out.println("Array2 = " + Arrays.toString(arr2[0]));
            System.out.println("Merged Array = " + Arrays.toString(newArray[3]));
            
            // set old array equal to new array
            laptops = newArray;
            return newArray;
            } else {
                System.out.println("Error adding laptop to list.");
                return laptops;
            }
            
        }
        
        
        /**
         * Prints out a string that contains GPU, CPU, battery life and id.
         */
        @Override
        public String toString() {
            
            return "GPU: " + gpu + " CPU: " + cpu + " Battery Life: " + batterylife + " ID: " + creatId();
        }
}

Advertisement

Answer

If you want a single Laptops object to continue updating, then you should initialize it once before your loop (I renamed your instance from “addLaptop” to “laptops” to remove ambiguity with the function with the same name).

Laptops laptops = new Laptops();
Scanner myObj = new Scanner(System.in);

int loop = 0;...

And then you want to remove this line (the one inside your loop, not the first one above the loop) entirely as it is the culprit:

Laptops addLaptop = new Laptops(gpu, cpu, batterylife);

You don’t need to reinitialize it in the loop, simply call addLaptop() (a member of the Laptop class), but passing your 3 parameters, gpu, cpu and batterylife into that function, so when you call that method, it is like:

laptops.addLaptop(gpu, cpu, batterylife);

What’s happening is that your code is continuously overwriting your old laptops with the new keyword.

Noticed also, your (input == 1) case should also remove the new laptop, and simply call

laptops.printAllLaptops();

so that it updates the instance of your instance of Laptops, not a new one.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement