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));
}
}
错误(stderr) 线程“主”中的异常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)
答案 0 :(得分:1)
如果我正确地理解了问题,则应该先进行int然后扫描n行并创建2维列表/数组的排序,然后再接受int有关该2维位置(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();
}
}