Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Exam;
- import java.util.Scanner;
- public class MouseAndCheese {
- static int startRow = 0;
- static int startCol = 0;
- static int bonus = 0;
- static int cheese = 0;
- static int cheeseEaten = 0;
- static boolean foundEnd = false;
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int territorySize = Integer.parseInt(scanner.nextLine());
- char[][] territory = new char[territorySize][territorySize];
- for (int row = 0; row < territorySize; row++) {
- String line = scanner.nextLine().replaceAll("\\s+", "");
- territory[row] = line.toCharArray();
- if (line.contains("M")) {
- startRow = row;
- startCol = line.indexOf("M");
- }
- for (char chars : territory[row]) {
- if (chars == 'B') {
- bonus++;
- }
- if (chars == 'c') {
- cheese++;
- }
- }
- }
- String command = scanner.nextLine();
- while (!command.equals("end")) {
- moveCommands(territory, command);
- // printField(territory);
- // System.out.println();
- if (foundEnd) {
- break;
- }
- command = scanner.nextLine();
- }
- if (cheeseEaten>=5) {
- System.out.println("Great job, the mouse is fed " + cheeseEaten + " cheeses!");
- }
- else {
- System.out.printf("The mouse couldn't eat the cheeses, she needed %d cheeses more.", (5-cheeseEaten));
- }
- System.out.println();
- printField(territory);
- }
- private static void moveCommands(char[][] territory, String command) {
- switch (command) {
- case "up":
- foundEnd = moveMouse(territory, startRow - 1, startCol, command);
- break;
- case "down":
- foundEnd = moveMouse(territory, startRow + 1, startCol, command);
- break;
- case "left":
- foundEnd = moveMouse(territory, startRow, startCol - 1, command);
- break;
- case "right":
- foundEnd = moveMouse(territory, startRow, startCol + 1, command);
- break;
- }
- }
- private static boolean moveMouse(char[][] territory, int newRow, int newCol, String command) {
- // System.out.println(command);
- int oldRow = startRow;
- int oldCol = startCol;
- startRow = newRow;
- startCol = newCol;
- if (startRow >= territory.length || startRow < 0) {
- territory[oldRow][oldCol] = '-';
- System.out.println("Where is the mouse?");
- return true;
- }
- if (startCol >= territory.length || startCol < 0) {
- territory[oldRow][oldCol] = '-';
- System.out.println("Where is the mouse?");
- return true;
- }
- char current = territory[startRow][startCol];
- territory[oldRow][oldCol] = '-';
- territory[startRow][startCol] = 'M';
- if (current == 'c') {
- cheese--;
- cheeseEaten++;
- }
- if (current == 'B') {
- moveCommands(territory, command);
- territory[startRow][startCol] = '-';
- }
- return false;
- }
- private static void printField(char[][] field) {
- for (char[] chars : field) {
- for (int j = 0; j < field.length; j++) {
- System.out.print(chars[j] + "");
- }
- System.out.println();
- }
- }
- }
Add Comment
Please, Sign In to add comment