【问题标题】:Index out of bounds (CSES permutations problem) java索引越界(CSES 排列问题)java
【发布时间】:2021-11-24 00:40:31
【问题描述】:
import java.util.*;
import java.io.*;
public class cses6 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        String m = "";

        ArrayList<Integer> even = new ArrayList<Integer>();
        ArrayList<Integer> odd = new ArrayList<Integer>();
        ArrayList<String> stringjoin = new ArrayList<String>();
        if (n == 1) {
            System.out.println(n);
        }
        if (1 < n && n< 4) {
            System.out.println("NO SOLUTION");
        }

        even.set(0, 4);
        even.set(1, 2);
        odd.add(0, 1);
        
        for (int i = 1; i < n+1 && i > 4; i++) {
            if (i % 2 == 0) {
                even.add(i);
            } else {
                odd.add(i);
            }


        }
        odd.addAll(even);

        for (int i = 1; i < odd.size(); i++) {
            m = Integer.toString(odd.get(i));
            stringjoin.set(i,m);
        }

        System.out.println(stringjoin.toString().replace(", ", " ").replace("[", "").replace("]",""));

        
    }
}

我的问题是: 输入

唯一的输入行包含一个整数 n。

输出

打印整数 1,2,…,n 的漂亮排列。如果有多个解决方案,您可以打印其中任何一个。如果没有解决方案,打印“NO SOLUTION”。

但是,我得到了索引越界错误。我的代码的哪一部分是错误的,我该如何解决这个错误? 错误发生在第 19 行

【问题讨论】:

  • 第 19 行是哪一行?请将完整的堆栈跟踪添加到您的问题中。
  • even.set(0, 4); 当你这样做时,even 列表仍然是空的
  • for (int i = 1; i &lt; n+1 &amp;&amp; i &gt; 4; i++) - 这是怎么回事?

标签: java permutation


【解决方案1】:

这里有错误的代码

even.set(0, 4);

原因就在这里

    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

您不能对空的 ArrayList 使用 set(int index, E element) 方法

【讨论】:

    猜你喜欢
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2015-05-13
    • 1970-01-01
    • 2019-02-18
    • 2018-11-19
    • 2013-03-30
    相关资源
    最近更新 更多