java - 当在前一个方法中设置值时,如何修复在一种方法中返回 null 的数组?
问题描述
我正在尝试在多个方法中使用单个数组;当我在另一种方法中定义数组的值后尝试打印它们时,我在 shop.main(shop.java:130) 的线程“main”java.lang.NullPointerException 中得到错误异常
public static int[] discount;
public static double[] price;
public static String[] name;
public static void setup(Scanner input, String[] name, double[] price, int[] discount) {
System.out.print("Please enter the number of items to setup shop: ");
do {
CheeseNum = input.nextInt();
if (CheeseNum < 0) {
System.out.print("Invalid Input. Enter a value > 0: ");
}
} while (CheeseNum < 0);
System.out.printf("\n");
discount = new int[CheeseNum];
price = new double[CheeseNum];
name = new String[CheeseNum];
for (int i = 0; i < CheeseNum; i++){
System.out.print("Enter the name of the " + numSuffix(i + 1) + " product: ");
name[i] = input.next();
System.out.printf("Enter the per package price of " + name[i] + ": ");
price[i] = input.nextDouble();
System.out.printf("Enter the number of packages ('x') to qualify for Special Discount (buy 'x' get 1 free) for " + name[i] + ", or 0 if no Special Discount offered:");
discount[i] = input.nextInt();
}
}
public static void buy(Scanner input, String[] name, int[] purchased) {
purchased = new int[CheeseNum];
for (int i = 0; i < CheeseNum; i++){
System.out.printf("\nEnter the number of " + name[i] + " packages to buy: ");
purchased[i] = input.nextInt();
shopBuyIns = shopBuyIns + purchased[i];
}
}
所以发生的事情是用户在设置中输入了数组的值,当我尝试在购买中使用这些值时,它告诉我数组为空。
解决方案
每当您在 java 中创建数组或对象时,java 都会为您创建的对象分配内存,并且该对象的变量名是指向它分配的内存位置的指针。在您的函数中,您创建了新数组,这意味着您在内存中为新数组分配了另一个位置,但是由于您是在函数范围内进行的,因此该数组将只存在于那里并且当您超出函数的范围时 java 的垃圾收集器将删除函数的所有局部变量 - 以及您的新数组!所以现在你的变量是一个指向内存中不存在的地方的指针,你得到NullPointerException
推荐阅读
- c++ - 强制执行 CMake 安装指令
- angular - NGXS 中的 DISPATCH 是什么意思?
- java - Spring WebClient 在 Tomcat 上留下开放会话
- python - 计算Python中另一个列表中每个嵌套列表的出现次数
- css - 引导按钮不会显示内联块
- reactjs - 如何在 React 中将函数设置为 useState 变量?
- r - 将数据透视表导出到 R markdown(用于 word 中的最终输出)
- java - 如何使用java动态计算模型中空字段的计数
- java - 在 Mac 上的 mvn 构建期间,Java 测试中的环境变量为空
- youtube-dl - 使用 youtube-dl 嵌入缩略图时是否可以不更改文件创建日期?