import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; /* Java application that reads a rectangular "map" from a file ** (whose name is specified either via a command line argument ** or, absent that, by the user in response to a prompt) and ** then has a MapRegionFinder object identify the regions within ** the map. Both the original map and the "map of region IDs" ** are displayed. ** Input data is assumed to be in the format illustrated by this example: ** +---------+ ** | 5 7 | // # rows and columns, respectively ** | AAABBCC | // 1st row ** | AABBBBC | // 2nd row ** | CCCBBCC | // etc., etc. ** | CCAAAAA | ** | AAABBBB | ** +---------+ */ public class MapRegionFinderApp { public static void main(String[] args) { // Establish the name of the input file. String inputFileName; if (args.length != 0) { inputFileName = args[0]; } else { inputFileName = getStringFromUser("Enter input file name: "); } doStuff(inputFileName); } private static void doStuff(String inputFileName) { char[][] theMap = readMap(inputFileName); // Create a MapRegionFinder object and feed the map to it. MapRegionFinder mrf = new MapRegionFinder(theMap); // Print the map and the map of computed region ID's System.out.println("The map:"); mrf.printMap(); System.out.println("\nRegion IDs:"); mrf.printRegionIds(); /* // This code segment finds the regions of the map when it is // interpreted in the "wraparound" fashion. mrf = new MapRegionFinder(theMap, true); System.out.println("\nRegion IDs (wraparound):"); mrf.printRegionIds(); */ } /* Returns a new map (an array of type char[][]) corresponding to that ** described by the data in the file having the specified name. ** The data there is assumed to be in the format described in the ** header comments. */ private static char[][] readMap(String fileName) { Scanner input = null; try { input = new Scanner(new File(fileName)); } catch (FileNotFoundException e) { System.out.println("Cannot find file named " + fileName); System.out.println("Execution is aborting."); System.exit(0); } int numRows = input.nextInt(); int numCols = input.nextInt(); input.nextLine(); char[][] theMap = new char[numRows][numCols]; for (int i=0; i != numRows; i++) { String line = input.nextLine(); for (int j=0; j != numCols; j++) { theMap[i][j] = line.charAt(j); } } return theMap; } /* Prints the specified prompt and returns the string entered ** in response by the user. */ private static String getStringFromUser(String prompt) { Scanner keyboard = new Scanner(System.in); System.out.print(prompt); String response = keyboard.nextLine().trim(); System.out.println(response); return response; } }