Java 用陣列畫圖再存入檔案的問題??(20點)

The programme will work by using a matrix as the drawing area, onto which filled rectangles of various sizes and formed from differing characters can be drawn. The inputs to the program are as follows:

* The height and width of the drawing area

* A sequence of rectangle specifications

Each rectangle specification consists of

* The coordinates of the top left corner

* The coordinates of the bottom right corner

* The character to be used in forming the filled rectangle

The origin (point (0,0)) of the drawing area is at the top left, and all rectangle coordinates are given in (row, column) form (rather than (x,y) form). The end of the sequence of rectangles is marked by a negative coordinate.

Your program must take all of its input from a file, and send its picture to a file. The names of the files must be given on the command line, e.g.

$ java Piccy picdata.txt picout.txt

For example, if your input file contains the following:

10

10

3

2

7

7

#

0

6

4

9

@

-1

then your program should create a 10x10 drawing area and draw 2 overlapping rectangles in it - one formed from the '#' character, and the other from the '@' character. The drawing that is written to the output file should look like this:

@@@@

@@@@

@@@@

####@@@@

####@@@@

######

######

######

1 個解答

評分
  • 1 0 年前
    最佳解答

    import java.util.Scanner;import java.io.File;import java.io.FileNotFoundException;import java.io.PrintStream;public class Graph {  // 圖形陣列的類別   char[][] graph;   // 內部二維陣列  Graph(int h, int w) {   // 圖形陣列的構建子, 接受寬跟高作為起始參數    graph = new char[h][w];    fill(0, 0, h-1, w-1, ' '); // 將整個內部陣列填為空白  }  public void fill(int top, int left,                    int bottom, int right, char ch) {  // 在指定的陣列填入特定字元       for (int i=top; i <= bottom; i++){      for (int j=left; j <= right; j++) {        graph[i][j] = ch;      }    }  }  public void print(PrintStream out) {       // 將圖形陣列輸出到指定的輸出    for (int i=0; i < graph.length; i++){      for (int j=0; j < graph[0].length; j++) {        out.print(graph[i][j]);      }      out.println("");    }  }  public static void main(String[] args) throws FileNotFoundException {    File fIn = new File(args[0]);  //      Scanner sc = new Scanner(fIn);    int h = sc.nextInt();   // 輸入高度    int w = sc.nextInt();   // 輸入寬度    Graph g = new Graph(h, w);    int top = sc.nextInt();    while (top >= 0 ) {      int  left= sc.nextInt();      int bottom = sc.nextInt();      int right = sc.nextInt();      char ch = sc.next().charAt(0);      g.fill(top, left, bottom, right, ch);      top = sc.nextInt();    }    sc.close();    g.print(new PrintStream(new File(args[1])));  }}

還有問題?馬上發問,尋求解答。