java - 如何重新初始化在 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 抱怨,因为数组之前已初始化(我不应该更改它)。
问题是,实际上有没有办法在给定代码的基础上构建,还是我必须删除它们的初始声明并重新开始?
解决方案
最好在需要时使用适当的值声明和初始化变量,而不必重新分配它们:
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
推荐阅读
- javascript - 带有 FlipClock.js 的货币符号
- javascript - 如何将 document.body.appendchild(' 定位到根文档而不是 iframe
- javascript - 在选择更改时打开一个新标签 - 仅适用于 Chrome
- java - 使用 parentId 将子关系设置为父级,并在一个事务中获取列表中所有子级的父级
- java - XML 签名的引用中的 DigestValues 来自哪里?
- python - 使用外键批量插入行并自动将行添加到引用的表中
- sql-server - 使用 (.dtsConfig) 文件将 SSIS 部署到目录
- javascript - 引导工具提示和选择下拉重叠问题
- jenkins - 如何在 Jenkins 中使用 configuration-as-code 插件配置 config-file-provider 文件
- entity-framework - 使用 EF Core 记录查询持续时间