Как мне запустить эту программу, когда я пытаюсь передать файлы через командную строку из редактируемых конфигураций, однако возникает ошибка? - PullRequest
0 голосов
/ 03 апреля 2020

/ ** * Класс функций промежуточного программного обеспечения, этот класс группирует функции *, которые не вписываются в другие классы, поскольку этот класс * не представляет никакой абстракции. * /

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.RuntimeException;
import java.util.ArrayList;
import java.util.Scanner;

public class Middleware {

    /**
      * Listens for the keystroke from the keyboard
      * from the user.
      * @return pressedKey - character pressed.
      */

    public static char readKeys() {
        if (StdDraw.hasNextKeyTyped()) {
            return StdDraw.nextKeyTyped();
        } else {
            return '1';
        }
    }

    /**
      * concatenates the lines in the input.
      * @param input - scanner object created from the moves file.
      * @return moves - the resulting string.
      */

    public static String readMoves(Scanner input) {
        StringBuilder moves = new StringBuilder("");

        while (input.hasNextLine()) {
            moves.append(input.nextLine());
        }
        return moves.toString();
    }

    /**
      * processes inputfile containing the board contents and constructs a
      * GameBoard object from it, throws an FileNotFound Exception if the file
      * is not found.
      * @param inputfile - file name that contains board input.
      * @return traversalBoard - An instance of the GameBoard class.
      */

    public static GameBoard parseArgs(String inputfile) throws FileNotFoundException {
        Scanner in = new Scanner(new File(inputfile));
        int boardHeight  = in.nextInt();
        in.hasNext(" ");
        int boardWidth   = in.nextInt();
        in.nextLine();
        GameBoard traversalBoard = new GameBoard(boardWidth, boardHeight);

        for (int i = 0; i < boardHeight; i++) {
            String currentLine = in.nextLine();
            for (int j = 0; j < boardWidth; j++) {
                if (!(currentLine.charAt(j) == '.')) { /* '.''s represent empty spaces. */
                    char symbol     = currentLine.charAt(j);
                    Position point  = new Position(j, boardHeight - i - 1);
                    GamePiece piece = new GamePiece(symbol, point);
                    traversalBoard.addGamePiece(piece);
                }
            }
        }
        return traversalBoard;
    }

    /**
      * an errorhandler in way, checks if a GameBoard board is valid by
      * checking the following:
      * The boards deminsions are in within the bounds of length 3 and 15
      * If the GameBoard instance has a player game piece
      * If the GameBoard instance has a target game piece
      * if any of these conditions are not met, a Runtime Exception error
      * is thrown to the user.
      * @param board - GameBoard instance to be evaluated.
      * @throws RuntimeException - error exception for board dimensions out of
      *     bounds.
      */

    public static void validateBoard(GameBoard board) {
        if (board.getPlayer() == null) {
            throw new RuntimeException("Error: GameBoard must have at most one player game piece");
        } else if (board.getTarget() == null) {
            throw new RuntimeException("Error: GameBoard must have at most one target game piece");
        } else if (board.getBoardHeight() > 15 && 3 < board.getBoardHeight()
                        || board.getBoardWidth() > 15 && 3 < board.getBoardWidth()) {
            throw new RuntimeException("Error: GameBoard dimensions out of bounds");
        }
    }

}


/**Compilation  : javac Traversal.java

Execution    : java Traversal args0 ----- GraphicsMode
                   : java Traversal args0 args1 ----- TextMode

Arguments    : args0 - boardfilename.txt
                     args1 - movesfilename.txt

Controls     : h - left movement
              l - right movement
              j - down movement
              k - up movement
**/



    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    public class Traversal {

        /**
        * Main client
        * takes a maximum of two commandline
        * arguments of filenames, and calls
        * a game mode as decided by number of
        * commandline arguments.
        */
        public static void main(String[] args) throws FileNotFoundException, InterruptedException {
            if (args.length == 1) {
                GameBoard board = Middleware.parseArgs(args[0]);
                Middleware.validateBoard(board);
                GraphicsMode.play(board);

            } else if (args.length == 2) {
                GameBoard board = Middleware.parseArgs(args[0]);
                Middleware.validateBoard(board);
                String moves = Middleware.readMoves(new Scanner(new File(args[1])));
                TextMode.play(board, moves);
            }
            exit();
        }

        /**
          * Sleep for 4000 microseconds to allow
          * the final event sound to finish
          * playing and then exits.
          */

        public static void exit() throws InterruptedException {
            Thread.sleep(4000);
            System.exit(0);
        }
    }

Я запустил этот код из командной строки, однако он выдал ошибку, и файлы, которые я хочу запустить, находятся в моей папке sr c. Поэтому мне интересно, если мне нужно ввести имена файлов и каталогов где-нибудь в коде, однако я пробовал это, и он не хочет запускать файлы, и он просто выходит с кодом 0. Ошибка появляется как:

Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at Middleware.parseArgs(Middleware.java:40)
    at Traversal.main(Traversal.java:9)
...