【问题标题】:Cannot invoke because Array[] is null [duplicate]无法调用,因为 Array[] 为空 [重复]
【发布时间】:2022-01-30 08:53:09
【问题描述】:

我还是编程新手,我想制作一个程序,该程序将接收用户的食物订单,直到用户按“n”停止。但我似乎无法让它像我想要的那样工作。

我希望我的输出是这样的。

Buy food: Burger
Order again(Y/N)? y
Buy Food: Pizza
Order again(Y/N)? n

You ordered: 
Burger
Pizza

但我现在的输出是这样的。

Buy food: Burger
Order again(Y/N)? y
Buy food: Pizza
Order again(Y/N)? n

You ordered: 
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Array.getFoodName()" because "food_arr2[i]" is null
    at Food.main(Food.java:50)

这是我的代码:

public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        Food food = new Food();  
        Array[] food_arr;

        boolean stop = false;
        String foodName;
        int k = 1;
        int j = 0;
        
        while(stop == false) {
            food_arr = new Array[k];

            System.out.print("Buy food: ");
            foodName = s.next();
            food_arr[j] = new Array(foodName);
            food.setFoodArray(food_arr);

            System.out.print("Order again(Y/N)? ");
            String decide = s.next();
            if(decide.equalsIgnoreCase("y")) {
                k++;
                j++;
            }
            else if(decide.equalsIgnoreCase("n")) {
                stop = true;
            }
        }

        Array[] food_arr2 = food.getFoodArray();

        for (int i = 0; i < food_arr2.length; ++i) {
            System.out.println("\nYou ordered: ");
            System.out.println(food_arr2[i].getFoodName()); //This line is the error according to my output
        }
    }

我不知道如何解决这个问题,我希望有人能帮助我。

【问题讨论】:

  • 错误来了,因为food.getFoodArray()返回null。你为什么不尝试通过if(food.getFoodArray() == null)检查它是否为null?
  • @SambhavKhandelwal 异常并不表示数组本身为空,它表示数组(foo_arr2[i])索引i处的值为空

标签: java arrays getter-setter encapsulation


【解决方案1】:

我想我看到了你试图用 k 值来设置你正在使用的数组的大小。 但是,对于 while 循环的每次迭代:

food_arr = new Array[k];

每次都会创建一个新的空数组!

例如,在第二次迭代中

food.setFoodArray(food_arr);

将 food 数组设置为 [null, "Pizza"]

即使这确实有效,但每次创建一个新数组也不是一种非常有效的方法。


我强烈建议使用不同的动态分配数据结构,例如 ArrayList,并将其定义在 while 循环范围之外。

ArrayList<Food> food_arr = new ArrayList<Food>() 
// Note that I'm just guessing the data type here - I can't see what you are actually using!   

while(stop == false) {

        System.out.print("Buy food: ");
        foodName = s.next();
        food_arr.add(foodName)
        
        // etc, etc
    }

food.setFoodArray(food_arr) 
// ! Note: You will need to convert the array list into an array
// ! or change the data struture in the Food class

// etc, etc

然而,这只是我脑海中浮现的第一个解决方案,检查不同类型的数据结构并思考如何自己设计这个程序!

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 2021-12-08
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-18
    • 2022-11-19
    相关资源
    最近更新 更多