gpt4 book ai didi

java - 如何将文件中的数字列表放入数组并返回数组

转载 作者:行者123 更新时间:2023-12-01 13:44:52 24 4
gpt4 key购买 nike

在此方法中,我尝试从传递到该方法的文件创建一个数组(该文件有一个数字列表),然后我想返回该数组。但是当我尝试运行我的代码时,会弹出错误,提示找不到符号“nums”。

我确信我有范围问题,但我不知道如何解决这个问题。

如何修复此代码以使其正确返回数组?

这是我的代码:

   //reads the numbers in the file and returns as an array
public static int [] listNumbers(Scanner input) {
while (input.hasNext()) {
int[] nums = new int[input.nextInt()];
}
return nums;
}

最佳答案

这里至少有两个问题。

首先,nums是在你的 while 中定义的循环,当你退出循环时它就会超出范围。这就是你的编译错误的原因。如果您想在循环完成后返回定义,则需要将定义移到循环之外。

但是,还有另一个问题,就是在读取整个文件之前,您不知道数组需要多大。创建 ArrayList<Integer> 会容易得多并向其中添加元素,然后在读取整个文件后将其转换为数组(如有必要)。或者只返回列表,而不是数组。

  public static List<Integer> listNumbers(Scanner input) {
List<Integer> nums = new ArrayList<Integer>();
while (input.hasNext()) {
nums.add(input.nextInt());
}
return nums;
}

关于java - 如何将文件中的数字列表放入数组并返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com