【问题标题】:Why isn't my Array updating outside of the method that it is set in after I assign it a new value?为什么我的数组在我为它分配新值后没有在设置的方法之外更新?
【发布时间】:2023-01-15 00:00:02
【问题描述】:

我有一个问题,当我在 addLaptop() 方法中组合两个数组 'laptops' 和 'arr2' 并创建第三个数组 'newArray' 以包含 'laptops' 和 'arr2' 的值然后设置 'laptops' 数组等于 'newArray' 的值并在我的 addLaptop() 方法中打印 'laptops' 'laptops' 的值将像我想要的那样等于 'newArray'。

但是,当我尝试从我的 printAllLaptops() 方法中获取“笔记本电脑”中的数据时,“笔记本电脑”数组中的值被设置回其原始值,而不是像我想要的那样设置为“newArray”的值成为。

我的问题是什么我不明白为什么这些值不会更新?我已经在这个问题上停留了几个小时,并尝试将“笔记本电脑”数组移动到我的不同方法中,并尝试设置笔记本电脑 = newArray 并且还尝试通过我的 addLaptop() 方法以几种不同的方式返回笔记本电脑。

调用我的方法的代码: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();
        }
    }
}

我的代码是问题所在: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();
        }
}

【问题讨论】:

  • 重现问题的完整程序在这里会有很大帮助。 minimal reproducible example
  • 发生这种情况是因为您每次使用 new 创建一个新的 Laptops 对象。修复起来并不完全直接,因为不清楚Laptops 代表什么:一个还是多个?它包含一个列表,就好像它代表许多笔记本电脑一样,但它是用单个 cpu/gpu 初始化的,就好像它是一台笔记本电脑一样。您应该考虑创建一个代表单个笔记本电脑对象的Laptop类,然后创建一个包含Laptop数组的LaptopList或LaptopCollection。或者,你可以给你的Laptops类一个.addNewLaptop(cpu, gpu, battery),这样它就可以被多次调用
  • 我已经添加了完整的程序,现在您应该可以将其复制并粘贴到您的 IDE 中,如果您愿意,可以重新创建问题。

标签: java arrays


【解决方案1】:

如果您希望单个 Laptops 对象继续更新,那么您应该在循环之前将其初始化一次(我将您的实例从“addLaptop”重命名为“laptops”以消除具有相同名称的函数的歧义)。

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

int loop = 0;...

然后您想完全删除这一行(循环内的那一行,而不是循环上方的第一行),因为它是罪魁祸首:

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

您不需要在循环中重新初始化它,只需调用 addLaptop()(Laptop 类的成员),但将 3 个参数 gpu、cpu 和 batterylife 传递给该函数,因此当您调用该方法时,它是喜欢:

laptops.addLaptop(gpu, cpu, batterylife);

发生的事情是您的代码不断地用 new 关键字覆盖您的旧笔记本电脑。

还注意到,你的 (input == 1) 案例也应该删除 new 笔记本电脑,然后简单地调用

laptops.printAllLaptops();

以便它更新您的笔记本电脑实例,而不是新实例。

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 2020-10-17
    • 1970-01-01
    • 2020-03-02
    • 2017-12-10
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 2018-07-03
    相关资源
    最近更新 更多