0

我是 Comp Sci 的学生,我的大学有一个 ACM 编程竞赛俱乐部。我刚刚开始,我正在解决其中一个问题。该程序在我运行时运行良好并且不会产生任何异常。但是,当我在运行测试和它给我的东西的网站上提交它时:

您的应用程序发生异常:

线程“主”java.util.NoSuchElementException 中的异常:在 Main.main(Main.java:16) 的 java.util.Scanner.nextLine(Scanner.java:1585) 处找不到行

代码:

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

public class Main
{
public static void main(String[] args)
{
    Scanner inMain = new Scanner(System.in);
    ArrayList<String> a = new ArrayList<String>();

    int q = inMain.nextInt();

    for (int j = 0; j < q; j++)
    {
        Scanner read = new Scanner(System.in);
        String temp = read.nextLine();
        a.add(temp);
    }

    int r = inMain.nextInt();

    for (int h = 0; h < r; h++)
    {
        int selection = inMain.nextInt();
        if (selection < 0 || selection > q)
        {
            System.out.println("Rule " + selection + ": No such rule");
        } else
        {
            System.out.println("Rule " + selection + ": "
                    + a.get(selection - 1));
        }
    }
}

}
4

1 回答 1

0

在访问之前检查下一行是否存在

for (int j = 0; j < q; j++)
{
    Scanner read = new Scanner(System.in);
    if (read.hasNextLine()){
        String temp = read.nextLine();
        a.add(temp);
    }
}
于 2013-11-18T20:02:15.983 回答