错误:“main”java.util.NoSuchElementException

时间:2013-11-07 10:50:45

标签: java exception

我想让用户输入任何输入文件FCITrecurse.in,输出打印出文件FCITrecurse.out。

所以,这是我的代码

    public static void main(String[] args) throws Exception {


    int numOfCommands;
    String command;

    // make input file
    File inputFile = new File("FCITrecurse.in");
    if (!inputFile.exists()) {
        System.out.println("Input file, " + inputFile + ", does not exist.");
        System.exit(0);
    }
    // make output file
    File outputFile = new File("FCITrecurse.out");

    // Make Scanner for input and Printwriter for output
    Scanner input = new Scanner(inputFile);

    PrintWriter output = new PrintWriter(outputFile);

    // Scan the # of commands from the file (the int on the first line of input file)
    numOfCommands = input.nextInt();


    // Now do a for loop over the number of commands
    for (int i = 0; i < numOfCommands; i++) {
        // Scan the next command from the input file
        command = input.next();

        // Now check which command was read, and call the appropriate methods

        // Command: FCITmultiply
        if (command.equals("FCITmultiply") == true) {
            // We call the WRAPPER method countDown()
            FCITmultiply(input, output);
        } // Command: FCITflip
        else if (command.equals("FCITflip") == true) {
            // We call the WRAPPER method FCITflip()
            FCITflip(input, output);
        } // Command: FCITshape
        else if (command.equals("FCITshape") == true) {
            // We call the WRAPPER method FCITshape()
            FCITshape(input, output);
        } // Command: FCITgame
        else if (command.equals("FCITgame") == true) {
            // We call the WRAPPER method FCITgame()
            FCITgame(input, output);
        } // WRONG CHOICE
        else {
            ; // do nothing
        }
    }

    // Close input and output
    input.close();
    output.close();

}

这是错误消息:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)enter code here
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at p.P.main(P.java:116)

这是第116行:

// Scan the # of commands from the file (the int on the first line of input file)
    int numOfCommands = input.nextInt();

它最初不接受输入?任何输入intstring

这里我的问题是什么?

如果我改变我的代码,它会起作用,但不会将输入保存在外部输入文件中

    // Make Scanner for input and Printwriter for output
    Scanner input = new Scanner(System.in);

1 个答案:

答案 0 :(得分:0)

如果您发布的代码准确无误,那么for循环命令的副本太多了。您正在运行循环体n 2 次而不是n次。

如果您的输入文件中包含0或1命令,您是否测试过该程序?

你的包装器方法是否以某种方式使用输入扫描器将它推进得太远了?