【问题标题】:how to put a list of numbers from a file into an array and return the array如何将文件中的数字列表放入数组并返回数组
【发布时间】:2013-12-24 09:00:35
【问题描述】:

在此方法中,我试图从传递给该方法的文件创建一个数组(该文件有一个数字列表),然后我想返回该数组。但是当我尝试运行我的代码时,会弹出错误,它找不到符号“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;
   }

【问题讨论】:

标签: java arrays file while-loop scope


【解决方案1】:

这里至少有两个问题。

首先,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;
  }

【讨论】:

    【解决方案2】:
        List<Integer> list = new ArrayList<Integer>();
        while(input.hasNext())
        {
            list.add(input.nextInt());
        }
    
        int size = list.size();
        int[] nums = new int[size];
    
        int counter = 0;
        for(Integer myInt : list)
        {
            nums[counter++] = myInt;
        }    
    
        return nums;
    

    此解决方案未经测试,但可以为您提供一些指导。这也符合西蒙所指的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      相关资源
      最近更新 更多