【问题标题】:How can I copy the elements on an array into another array with a different size?如何将数组上的元素复制到另一个大小不同的数组中?
【发布时间】:2021-10-07 01:34:06
【问题描述】:

我正在处理一个包含数组的项目。我正在使用一种将值添加到大小为 20 的数组的方法。我应该能够更改数组的大小,同时还将值从前一个数组传输到新数组。我使用了 Array.copyOfRange ,它应该可以工作,但由于某种原因,当我运行代码并尝试更改数组的大小时。我收到一条错误消息,指出索引超出范围。有人可以帮我弄清楚为什么它会说什么时候应该起作用吗?

import java.util.Scanner;
import java.util.Arrays;

public class IntBag2 {
    private static final int INITIAL_SIZE = 20;
    private static int[] bag;
    private int capacity;

    public IntBag2() {
        bag = new int[INITIAL_SIZE];
    }

    public IntBag2(int capacity) {
        bag = new int[capacity];
    }

    public boolean add(int item) {
        if (capacity == bag.length)
            return false;

        bag[capacity++] = item;

        return true;
    }

    public void changeCapacity(int newCapacity) {
        bag = Arrays.copyOfRange(bag, 0, newCapacity);
    }

    @Override
    public String toString() {
        String result = "Bag: ";
        for (int i = 0; i < capacity; i++)
            result += bag[i] + " ";
        return result;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        IntBag2 intBag = new IntBag2();
        boolean done = false;

        while (!done) {
            System.out.println("1. Add an Item to the Array");
            System.out.println("2. Change Length of Array");
            System.out.println("3. toString");
            switch (input.nextInt()) {
            case 1:
                System.out.println("Add an Item to the Array");
                intBag.add(input.nextInt());
                break;
            case 2:
                System.out.println("Change Length of Array");
                intBag.changeCapacity(input.nextInt());
                break;
            case 3:
                System.out.println("toString");
                System.out.println(intBag.toString());
                break;
            }
        }
        input.close();
    }

}

【问题讨论】:

    标签: java arrays java.util.scanner


    【解决方案1】:

    因为在您的 changeCapacity 函数中,您没有使用传递的 newCapacity 更新容量字段。

    public void changeCapacity(int newCapacity) {
            bag = Arrays.copyOfRange(bag, 0, newCapacity);
            capacity = newCapacity;
        }
    

    只需用上面的代码替换你的 changeCapacity 函数,它应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 2017-01-22
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 2020-07-30
      相关资源
      最近更新 更多