// The Canvas object plots objects in a two-dimensional array. // The write method writes these objects to an output file. import java.io.PrintWriter; import java.io.FileNotFoundException; public class Canvas { private String fileName; private int width; private int height; private char[ ][ ] array; public Canvas(String theFileName, int theWidth, int theHeight) { fileName = theFileName; if (theWidth >= 1) width = theWidth; else width = 1; if (theHeight >= 1) height = theHeight; else height = 1; array = new char[height][width]; } public String getFileName( ) { return fileName; } public int getWidth( ) { return width; } public int getHeight( ) { return height; } public void setPoint(char symbol, int x, int y) { if (0 <= x && x < width && 0 <= y && y < height) array[y][x] = symbol; } protected void write( ) throws FileNotFoundException { // Create PrintWriter object. PrintWriter pw = new PrintWriter(fileName); // Plot header for file. pw.print(" "); for(int i = 0; i < width; i++) if (i / 10 >= 1) pw.print(i / 10); else pw.print(" "); pw.println( ); pw.print(" "); for(int i = 0; i < width; i++) pw.print(i % 10); pw.println( ); // Write plot to output file. for(int j = 0; j < height; j++) { pw.printf("%2d", j); for(int i = 0; i < width; i++) pw.print(array[j][i]); pw.println( ); } pw.close( ); } public String toString( ) { return String.format("File:%s %dx%d", fileName, width, height); } public static void main(String[ ] args) throws FileNotFoundException { Canvas c = new Canvas("output.txt", 100, 50); System.out.println("Canvas filename is " + c.getFileName( )); System.out.println("Canvas width is " + c.getWidth( )); System.out.println("Canvas height is " + c.getHeight( )); c.setPoint('$', 30, 40); c.setPoint('#', 50, 20); c.write( ); } }