SlideShare a Scribd company logo
1 of 7
Download to read offline
Java Question: Consider a maze made up of a rectangular array of squares. The maze will
contain a character (either +, -, or |) to represent a blocked square, and to form the walls of the
maze. Mazes will have only one entrance at the Coordinate (0, 1), with only one exit in the lower
right hand corner of the maze. Beginning at the entrance to the maze, find a path to the exit at the
bottom right of the maze. You may only move up, down, left, and right. Each square in the maze
can be in one of four states: clear (space), blocked (X), path (.), or visited (*). Initially, after the
maze has been read in from the file, each square will be either clear or blocked. If a square lies
on a successful path, mark it with a period. If you visit a square but it does not lead to a
successful path, mark it as visited with an asterisk.
Solution
import java.io.*;
class Maze
{
// Any MazeSquare field is true if the corresponding
// wall exists, and false otherwise.
class MazeSquare
{
public boolean hasTopWall;
public boolean hasRightWall;
public boolean hasLeftWall;
public boolean hasBottomWall;
public MazeSquare()
{
hasTopWall = hasRightWall = hasLeftWall = hasBottomWall = false;
}
}
// This Exception class will help pinpoint format errors in the data file.
class MazeFormatException extends Exception
{
public final static int noError = 0;
public final static int badRowAndColumnCounts = 1;
public final static int wrongNumberOfEntriesInRow = 2;
public final static int badEntry = 3;
public int lineNumber;
public int problem;
public MazeFormatException( int line, int prob )
{
lineNumber = line;
problem = prob;
}
}
// Number of rows and columns in the maze.
private int nRows;
private int nColumns;
// The array of maze squares themselves.
MazeSquare[][] square;
public static void main( String[] args )
{
if( args.length != 1 )
{
System.err.println( "Usage: java Maze mazeFileName" );
System.exit( 1 );
}
Maze knosos = null;
try
{
knosos = new Maze( args[0] );
}
catch( FileNotFoundException e )
{
System.err.println( "Can't open " + args[0] + ". Check your spelling." );
System.exit( 1 );
}
catch( IOException e )
{
System.err.println( "Severe input error. I give up." );
System.exit( 1 );
}
catch( MazeFormatException e )
{
switch( e.problem )
{
case MazeFormatException.badRowAndColumnCounts:
System.err.println( args[0] + ", line " + e.lineNumber + ": row and column counts
expected" );
break;
case MazeFormatException.wrongNumberOfEntriesInRow:
System.err.println( args[0] + ", line " + e.lineNumber + ": wrong number of entries"
);
break;
case MazeFormatException.badEntry:
System.err.println( args[0] + ", line " + e.lineNumber + ": non-hexadecimal digit
detected" );
break;
default:
System.err.println( "This should never get printed." );
break;
}
System.exit( 1 );
}
knosos.print( System.out );
}
public Maze()
{
square = null;
nRows = nColumns = 0;
}
public Maze( String fileName ) throws FileNotFoundException, IOException,
MazeFormatException
{
BufferedReader in = null;
in = new BufferedReader( new FileReader( fileName ) );
load( in );
in.close();
}
public void load( BufferedReader in ) throws MazeFormatException
{
String line;
String[] tokens;
int lineNumber = 0;
// Get the number of rows and columns. Protect
// against out-of-range values.
try
{
line = in.readLine();
lineNumber++;
tokens = line.split( "s+" );
nRows = Integer.parseInt( tokens[0] );
nColumns = Integer.parseInt( tokens[1] );
if( nRows <= 0 || nColumns <= 0 )
throw new Exception();
}
catch( Exception e )
{
throw new MazeFormatException( lineNumber,
MazeFormatException.badRowAndColumnCounts );
}
// Allocate the 2D array of MazeSquares.
square = new MazeSquare[nRows][nColumns];
for( int i=0; i < nRows; i++ )
for( int j=0; j < nColumns; j++ )
square[i][j] = new MazeSquare();
// Read the square values from input into the array of MazeSquares.
for( int i=0; i < nRows; i++ )
{
try
{
line = in.readLine();
lineNumber++;
tokens = line.split( "s+" );
if( tokens.length != nColumns )
throw new Exception();
}
catch( Exception e )
{
throw new MazeFormatException( lineNumber,
MazeFormatException.wrongNumberOfEntriesInRow );
}
for( int j=0; j < nColumns; j++ )
{
int squareValue;
try
{
squareValue = Integer.parseInt( tokens[j], 16 );
}
catch( NumberFormatException e )
{
throw new MazeFormatException( lineNumber, MazeFormatException.badEntry );
}
// These are "bitwise AND" operations. We'll discuss them in class.
square[i][j].hasTopWall = ((squareValue & 1) != 0);
square[i][j].hasRightWall = ((squareValue & 2) != 0);
square[i][j].hasBottomWall = ((squareValue & 4) != 0);
square[i][j].hasLeftWall = ((squareValue & 8) != 0);
}
}
}
public void print( PrintStream out )
{
int i, j;
for( i=0; i < nRows; i++ )
{
// Draw the top walls of this row of squares.
out.print( '+' );
for( j=0; j < nColumns; j++ )
{
if( i > 0 && square[i][j].hasTopWall != square[i-1][j].hasBottomWall )
out.print( "xxx+" );
else if( square[i][j].hasTopWall )
out.print( "---+" );
else
out.print( " +" );
}
out.println();
// Draw the left and right walls of this row of squares.
if( nColumns > 0 && square[i][0].hasLeftWall )
out.print( '|' );
else
out.print( ' ' );
for( j=0; j < nColumns; j++ )
{
if( j < nColumns - 1 && square[i][j].hasRightWall != square[i][j+1].hasLeftWall )
out.print( " X" );
else if( square[i][j].hasRightWall )
out.print( " |" );
else
out.print( " " );
}
out.println();
}
if( nRows > 0 )
{
// Draw the bottom walls of the bottom row of squares.
out.print( '+' );
for( j=0; j < nColumns; j++ )
{
if( square[nRows-1][j].hasBottomWall )
out.print( "---+" );
else
out.print( " +" );
}
out.println();
}
}
}

More Related Content

Similar to Java Question Consider a maze made up of a rectangular array of squ.pdf

13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
Abdul Samee
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
retronym
 
About java
About javaAbout java
About java
Jay Xu
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
wpgreenway
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 

Similar to Java Question Consider a maze made up of a rectangular array of squ.pdf (20)

Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
 
Lecture2
Lecture2Lecture2
Lecture2
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In Scala
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Kotlin decompiled
Kotlin decompiledKotlin decompiled
Kotlin decompiled
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
About java
About javaAbout java
About java
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
11.ppt
11.ppt11.ppt
11.ppt
 
strings.ppt
strings.pptstrings.ppt
strings.ppt
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 

More from wasemanivytreenrco51

Explain in detail how OFDM helps mitigates multipath fading effects..pdf
Explain in detail how OFDM helps mitigates multipath fading effects..pdfExplain in detail how OFDM helps mitigates multipath fading effects..pdf
Explain in detail how OFDM helps mitigates multipath fading effects..pdf
wasemanivytreenrco51
 
Describe briefly each mouth part of the grasshopper. b. Describe how.pdf
Describe briefly each mouth part of the grasshopper.  b. Describe how.pdfDescribe briefly each mouth part of the grasshopper.  b. Describe how.pdf
Describe briefly each mouth part of the grasshopper. b. Describe how.pdf
wasemanivytreenrco51
 
Contrast the views of Piaget and Bandura on how children develop..pdf
Contrast the views of Piaget and Bandura on how children develop..pdfContrast the views of Piaget and Bandura on how children develop..pdf
Contrast the views of Piaget and Bandura on how children develop..pdf
wasemanivytreenrco51
 
What is an Accountable Care Organizations (ACO) How does an ACOs .pdf
What is an Accountable Care Organizations (ACO) How does an ACOs .pdfWhat is an Accountable Care Organizations (ACO) How does an ACOs .pdf
What is an Accountable Care Organizations (ACO) How does an ACOs .pdf
wasemanivytreenrco51
 
Prove asymptotic upper and lower hounds for each of the following sp.pdf
Prove asymptotic upper and lower hounds for each of the following  sp.pdfProve asymptotic upper and lower hounds for each of the following  sp.pdf
Prove asymptotic upper and lower hounds for each of the following sp.pdf
wasemanivytreenrco51
 
Please create an infographic for medical fraud! Thank you so much.pdf
Please create an infographic for medical fraud! Thank you so much.pdfPlease create an infographic for medical fraud! Thank you so much.pdf
Please create an infographic for medical fraud! Thank you so much.pdf
wasemanivytreenrco51
 
Internet Programming. For event-driven architecture, how does pollin.pdf
Internet Programming. For event-driven architecture, how does pollin.pdfInternet Programming. For event-driven architecture, how does pollin.pdf
Internet Programming. For event-driven architecture, how does pollin.pdf
wasemanivytreenrco51
 
PCAOB Please respond to the followingGo to the PCAOB Website..pdf
PCAOB Please respond to the followingGo to the PCAOB Website..pdfPCAOB Please respond to the followingGo to the PCAOB Website..pdf
PCAOB Please respond to the followingGo to the PCAOB Website..pdf
wasemanivytreenrco51
 

More from wasemanivytreenrco51 (20)

Explain what differential cell affinity is, how this process is acco.pdf
Explain what differential cell affinity is, how this process is acco.pdfExplain what differential cell affinity is, how this process is acco.pdf
Explain what differential cell affinity is, how this process is acco.pdf
 
Explain in detail how OFDM helps mitigates multipath fading effects..pdf
Explain in detail how OFDM helps mitigates multipath fading effects..pdfExplain in detail how OFDM helps mitigates multipath fading effects..pdf
Explain in detail how OFDM helps mitigates multipath fading effects..pdf
 
Entamoeba histolytica is an amoeba responsible for the gastrointestin.pdf
Entamoeba histolytica is an amoeba responsible for the gastrointestin.pdfEntamoeba histolytica is an amoeba responsible for the gastrointestin.pdf
Entamoeba histolytica is an amoeba responsible for the gastrointestin.pdf
 
Describe briefly each mouth part of the grasshopper. b. Describe how.pdf
Describe briefly each mouth part of the grasshopper.  b. Describe how.pdfDescribe briefly each mouth part of the grasshopper.  b. Describe how.pdf
Describe briefly each mouth part of the grasshopper. b. Describe how.pdf
 
Contrast the views of Piaget and Bandura on how children develop..pdf
Contrast the views of Piaget and Bandura on how children develop..pdfContrast the views of Piaget and Bandura on how children develop..pdf
Contrast the views of Piaget and Bandura on how children develop..pdf
 
Compute the probability of event E if the odds in favor of E are 31.pdf
Compute the probability of event E if the odds in favor of E are  31.pdfCompute the probability of event E if the odds in favor of E are  31.pdf
Compute the probability of event E if the odds in favor of E are 31.pdf
 
Compare and contrast the world population with that of the United St.pdf
Compare and contrast the world population with that of the United St.pdfCompare and contrast the world population with that of the United St.pdf
Compare and contrast the world population with that of the United St.pdf
 
8. What protocol is are layers 6 and 7 of the OSI model based on.pdf
8. What protocol is are layers 6 and 7 of the OSI model based on.pdf8. What protocol is are layers 6 and 7 of the OSI model based on.pdf
8. What protocol is are layers 6 and 7 of the OSI model based on.pdf
 
Which statement is true of serous membranesA) They line closed cavi.pdf
Which statement is true of serous membranesA) They line closed cavi.pdfWhich statement is true of serous membranesA) They line closed cavi.pdf
Which statement is true of serous membranesA) They line closed cavi.pdf
 
Which of the following is not included in the calculation of the VIX .pdf
Which of the following is not included in the calculation of the VIX .pdfWhich of the following is not included in the calculation of the VIX .pdf
Which of the following is not included in the calculation of the VIX .pdf
 
What is an Accountable Care Organizations (ACO) How does an ACOs .pdf
What is an Accountable Care Organizations (ACO) How does an ACOs .pdfWhat is an Accountable Care Organizations (ACO) How does an ACOs .pdf
What is an Accountable Care Organizations (ACO) How does an ACOs .pdf
 
True or false A selective force (such as antibiotics) must be prese.pdf
True or false A selective force (such as antibiotics) must be prese.pdfTrue or false A selective force (such as antibiotics) must be prese.pdf
True or false A selective force (such as antibiotics) must be prese.pdf
 
The receptors in the feedback loop regulating ADH secretion are osmor.pdf
The receptors in the feedback loop regulating ADH secretion are osmor.pdfThe receptors in the feedback loop regulating ADH secretion are osmor.pdf
The receptors in the feedback loop regulating ADH secretion are osmor.pdf
 
The UV spectrum of the hot B0V star is significantly below the conti.pdf
The UV spectrum of the hot B0V star is significantly below the conti.pdfThe UV spectrum of the hot B0V star is significantly below the conti.pdf
The UV spectrum of the hot B0V star is significantly below the conti.pdf
 
Q2 For any drosophila population, what is the proportion of live ho.pdf
Q2 For any drosophila population, what is the proportion of live ho.pdfQ2 For any drosophila population, what is the proportion of live ho.pdf
Q2 For any drosophila population, what is the proportion of live ho.pdf
 
Prove asymptotic upper and lower hounds for each of the following sp.pdf
Prove asymptotic upper and lower hounds for each of the following  sp.pdfProve asymptotic upper and lower hounds for each of the following  sp.pdf
Prove asymptotic upper and lower hounds for each of the following sp.pdf
 
pls show details.thx 1. Consider the vectors v1 (a Find the projecti.pdf
pls show details.thx 1. Consider the vectors v1 (a Find the projecti.pdfpls show details.thx 1. Consider the vectors v1 (a Find the projecti.pdf
pls show details.thx 1. Consider the vectors v1 (a Find the projecti.pdf
 
Please create an infographic for medical fraud! Thank you so much.pdf
Please create an infographic for medical fraud! Thank you so much.pdfPlease create an infographic for medical fraud! Thank you so much.pdf
Please create an infographic for medical fraud! Thank you so much.pdf
 
Internet Programming. For event-driven architecture, how does pollin.pdf
Internet Programming. For event-driven architecture, how does pollin.pdfInternet Programming. For event-driven architecture, how does pollin.pdf
Internet Programming. For event-driven architecture, how does pollin.pdf
 
PCAOB Please respond to the followingGo to the PCAOB Website..pdf
PCAOB Please respond to the followingGo to the PCAOB Website..pdfPCAOB Please respond to the followingGo to the PCAOB Website..pdf
PCAOB Please respond to the followingGo to the PCAOB Website..pdf
 

Recently uploaded

Recently uploaded (20)

Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 

Java Question Consider a maze made up of a rectangular array of squ.pdf

  • 1. Java Question: Consider a maze made up of a rectangular array of squares. The maze will contain a character (either +, -, or |) to represent a blocked square, and to form the walls of the maze. Mazes will have only one entrance at the Coordinate (0, 1), with only one exit in the lower right hand corner of the maze. Beginning at the entrance to the maze, find a path to the exit at the bottom right of the maze. You may only move up, down, left, and right. Each square in the maze can be in one of four states: clear (space), blocked (X), path (.), or visited (*). Initially, after the maze has been read in from the file, each square will be either clear or blocked. If a square lies on a successful path, mark it with a period. If you visit a square but it does not lead to a successful path, mark it as visited with an asterisk. Solution import java.io.*; class Maze { // Any MazeSquare field is true if the corresponding // wall exists, and false otherwise. class MazeSquare { public boolean hasTopWall; public boolean hasRightWall; public boolean hasLeftWall; public boolean hasBottomWall; public MazeSquare() { hasTopWall = hasRightWall = hasLeftWall = hasBottomWall = false; } } // This Exception class will help pinpoint format errors in the data file. class MazeFormatException extends Exception { public final static int noError = 0; public final static int badRowAndColumnCounts = 1; public final static int wrongNumberOfEntriesInRow = 2; public final static int badEntry = 3;
  • 2. public int lineNumber; public int problem; public MazeFormatException( int line, int prob ) { lineNumber = line; problem = prob; } } // Number of rows and columns in the maze. private int nRows; private int nColumns; // The array of maze squares themselves. MazeSquare[][] square; public static void main( String[] args ) { if( args.length != 1 ) { System.err.println( "Usage: java Maze mazeFileName" ); System.exit( 1 ); } Maze knosos = null; try { knosos = new Maze( args[0] ); } catch( FileNotFoundException e ) { System.err.println( "Can't open " + args[0] + ". Check your spelling." ); System.exit( 1 ); } catch( IOException e ) { System.err.println( "Severe input error. I give up." ); System.exit( 1 ); } catch( MazeFormatException e )
  • 3. { switch( e.problem ) { case MazeFormatException.badRowAndColumnCounts: System.err.println( args[0] + ", line " + e.lineNumber + ": row and column counts expected" ); break; case MazeFormatException.wrongNumberOfEntriesInRow: System.err.println( args[0] + ", line " + e.lineNumber + ": wrong number of entries" ); break; case MazeFormatException.badEntry: System.err.println( args[0] + ", line " + e.lineNumber + ": non-hexadecimal digit detected" ); break; default: System.err.println( "This should never get printed." ); break; } System.exit( 1 ); } knosos.print( System.out ); } public Maze() { square = null; nRows = nColumns = 0; } public Maze( String fileName ) throws FileNotFoundException, IOException, MazeFormatException { BufferedReader in = null; in = new BufferedReader( new FileReader( fileName ) ); load( in ); in.close();
  • 4. } public void load( BufferedReader in ) throws MazeFormatException { String line; String[] tokens; int lineNumber = 0; // Get the number of rows and columns. Protect // against out-of-range values. try { line = in.readLine(); lineNumber++; tokens = line.split( "s+" ); nRows = Integer.parseInt( tokens[0] ); nColumns = Integer.parseInt( tokens[1] ); if( nRows <= 0 || nColumns <= 0 ) throw new Exception(); } catch( Exception e ) { throw new MazeFormatException( lineNumber, MazeFormatException.badRowAndColumnCounts ); } // Allocate the 2D array of MazeSquares. square = new MazeSquare[nRows][nColumns]; for( int i=0; i < nRows; i++ ) for( int j=0; j < nColumns; j++ ) square[i][j] = new MazeSquare(); // Read the square values from input into the array of MazeSquares. for( int i=0; i < nRows; i++ ) { try { line = in.readLine(); lineNumber++;
  • 5. tokens = line.split( "s+" ); if( tokens.length != nColumns ) throw new Exception(); } catch( Exception e ) { throw new MazeFormatException( lineNumber, MazeFormatException.wrongNumberOfEntriesInRow ); } for( int j=0; j < nColumns; j++ ) { int squareValue; try { squareValue = Integer.parseInt( tokens[j], 16 ); } catch( NumberFormatException e ) { throw new MazeFormatException( lineNumber, MazeFormatException.badEntry ); } // These are "bitwise AND" operations. We'll discuss them in class. square[i][j].hasTopWall = ((squareValue & 1) != 0); square[i][j].hasRightWall = ((squareValue & 2) != 0); square[i][j].hasBottomWall = ((squareValue & 4) != 0); square[i][j].hasLeftWall = ((squareValue & 8) != 0); } } } public void print( PrintStream out ) { int i, j; for( i=0; i < nRows; i++ ) { // Draw the top walls of this row of squares. out.print( '+' );
  • 6. for( j=0; j < nColumns; j++ ) { if( i > 0 && square[i][j].hasTopWall != square[i-1][j].hasBottomWall ) out.print( "xxx+" ); else if( square[i][j].hasTopWall ) out.print( "---+" ); else out.print( " +" ); } out.println(); // Draw the left and right walls of this row of squares. if( nColumns > 0 && square[i][0].hasLeftWall ) out.print( '|' ); else out.print( ' ' ); for( j=0; j < nColumns; j++ ) { if( j < nColumns - 1 && square[i][j].hasRightWall != square[i][j+1].hasLeftWall ) out.print( " X" ); else if( square[i][j].hasRightWall ) out.print( " |" ); else out.print( " " ); } out.println(); } if( nRows > 0 ) { // Draw the bottom walls of the bottom row of squares. out.print( '+' ); for( j=0; j < nColumns; j++ ) { if( square[nRows-1][j].hasBottomWall ) out.print( "---+" ); else out.print( " +" );