【问题标题】:why am I getting this erroneous output?为什么我会得到这个错误的输出?
【发布时间】:2019-01-25 05:21:23
【问题描述】:

https://www.hackerrank.com/challenges/java-arraylist/probleminput

5

5 41 77 74 22 44

1 12

4 37 34 36 52

0

3 20 22 33

5

1 3

3 4

3 1

4 3

5 5

样本输出

74

52

37

错误!

错误!

 import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    ArrayList array[] = new ArrayList[n];
    for(int i = 0; i < n; ++i)
    {
        ArrayList list = new ArrayList();
        int no = sc.nextInt();
        while(no != '\n')
        {
             list.add(no);
             no = sc.nextInt(); 
        }
        array[i] = list;
    }

    int k = sc.nextInt();
    int l = sc.nextInt();
    System.out.println(array[k].get(l));
}

}

错误(标准错误) 线程“主”java.util.NoSuchElementException 中的异常

at java.util.Scanner.throwFor(Scanner.java:862)

at java.util.Scanner.next(Scanner.java:1485)

at java.util.Scanner.nextInt(Scanner.java:2117)

at java.util.Scanner.nextInt(Scanner.java:2076)

at Solution.main(Solution.java:18)

【问题讨论】:

  • 你想通过这个程序达到什么目的?
  • @NicholasK ive 给出了上一节中的演示 ..
  • @LanaLightman 上面给出的链接不再起作用,你能用hackerrank的原始问题更新问题吗

标签: java arrays list


【解决方案1】:

如果我正确理解了这个问题,它应该首先扫描 n 行并创建某种二维列表/数组,然后应该接受关于这个二维中位置 (x,y) 的问题将超出范围的对象覆盖为“错误!”。

import java.util.ArrayList;
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
    /*
     * Enter your code here. Read input from STDIN. Print output to STDOUT.
     * Your class should be named Solution.
     */
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    sc.nextLine();
    ArrayList array[] = new ArrayList[n];
    for (int i = 0; i < n; i++) {
        ArrayList list = new ArrayList();
        Scanner linSc = new Scanner(sc.nextLine());
        while (linSc.hasNextInt()) {
            list.add(linSc.nextInt());
        }
        linSc.close();
        array[i] = list;
    }
    n = sc.nextInt();
    for (int i = 0; i < n; i++) {
        int k = sc.nextInt();
        int l = sc.nextInt();
            try {
                System.out.println(array[k - 1].get(l));
            } catch (IndexOutOfBoundsException e) {
                System.out.println("ERROR!");
            }
        }
        sc.close();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 2012-04-26
    • 2022-01-19
    • 2022-12-06
    • 2021-11-12
    相关资源
    最近更新 更多