0

我想在文件 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);
4

1 回答 1

0

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

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

您的包装器方法是否以某种方式使用输入扫描器,从而将其推进得太远?

于 2013-11-07T13:52:31.250 回答