首页 > 解决方案 > 如何重新初始化在 Java 中使用 null 值预定义的数组?

问题描述

所以我应该完成下面的程序,该程序根据用户的 int 输入确定数组的大小。

    public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       int userInput = -1;
       int[] userData = null;

但是程序首先将数组声明为: int[] userData = null;

它还首先将用户输入变量声明为 -1: int userInput = -1;

程序的问题是基于使用从用户扫描的 int 变量作为给定数组的长度重新初始化这个数组: userInput = scan.nextInt(); 所以我尝试使用新输入重新初始化数组: int[] userData = new int[userInput]; 但不出所料,Java 抱怨,因为数组之前已初始化(我不应该更改它)。

问题是,实际上有没有办法在给定代码的基础上构建,还是我必须删除它们的初始声明并重新开始?

标签: javaarrays

解决方案


最好在需要时使用适当的值声明和初始化变量,而不必重新分配它们:

Scanner scan = new Scanner(System.in);
int userInput = scan.nextInt(); // no need to set to -1
int[] userData = new int[userInput]; // no need to set to null

推荐阅读