如何解决错误:类型Integer不可见

时间:2018-11-02 18:20:20

标签: java arrays arraylist

我创建了一个ArrayList,但是当我尝试访问其中的元素时,我不断收到错误type Integer is not visible.,并使用名为Scanner的{​​{1}},我读取了输入从文件中创建一个in,然后创建一个array

ArrayList

但是,当我尝试通过创建名为int n = in.nextInt(); int[] curr = new int[n]; for (int i = 0; i < n; i++) { curr[i] = in.nextInt(); } ArrayList<Integer> order = new ArrayList<>(); for (int item: curr) order.add(item); 的{​​{1}}变量并运行order来访问int中的元素时,我总是遇到上述错误。我该如何解决?

谢谢, 萨蒂亚

2 个答案:

答案 0 :(得分:-1)

您可以尝试使用以下代码:

private static Scanner in = new Scanner(System.in);

public static void main(String args[]) {
    System.out.print("array length = ");
    int n = in.nextInt();
    int[] curr = new int[n];
    for (int i = 0; i < n; i++) {
        System.out.print("item"+i+" = ");
        curr[i] = in.nextInt();
    }
    ArrayList<Integer> order = new ArrayList<>();
    for (int item: curr) order.add(item);

    System.out.print("idx = ");
    int idx = in.nextInt();

    if (idx<order.size()){
        System.out.println(order.get(idx));
    } else {
        System.out.println("idm out of bounds...\n" +
                "result with modulo length of list:");
        System.out.println(order.get(idx%order.size()));
    }
}

答案 1 :(得分:-1)

您也可以尝试使用此代码。

    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int[] curr = new int[n];
    for (int i = 0; i < n; i++) {
        curr[i] = in.nextInt();
    }

    ArrayList<Integer> order = new ArrayList<>();
    for (int item : curr)
        order.add(item);

    int size = order.size();

    while (true) {
        System.out.print("index= ");
        int idx = in.nextInt();

        if (idx < size) {
            System.out.println(order.get(idx));
            break;
        }
        System.out.println("Error : indexOutofBoundException");
        System.out.println("Try again!");
    }
}