Saturday 15 February 2014

java - Make a Grid from a string in a text file -



java - Make a Grid from a string in a text file -

i have 3 run arguments min width, max width , text file name. text files filled 1 long string of random characters. want set each character grid spot. string file. how create grid?

class gridcipher{ static int mingridwidth; static int maxgridwidth; static file inputfile; public static void main(string[] args) throws filenotfoundexception { if (handlearguments(args)) processinput(); } static final string usage = "usage: gridwriter min_width max_width input_file_name"; static boolean handlearguments(string[] args) { // check right number of arguments if (args.length != 3) { system.out.println("wrong number of command line arguments."); system.out.println(usage); homecoming false; } seek { mingridwidth = integer.parseint(args[0]); maxgridwidth = integer.parseint(args[1]); } grab (numberformatexception ex) { system.out.println("min_width , max_width must integers."); system.out.println(usage); homecoming false; } inputfile = new file(args[2]); if (!inputfile.canread()) { system.out.println("the file " + args[2] + " cannot opened input."); homecoming false; } homecoming true; } static void processinput() throws filenotfoundexception { scanner input = new scanner(inputfile); string line = input.nextline(); int length = line.length(); // number of characters. // seek each width in appropriate range (int width = mingridwidth; width <= maxgridwidth; width++) { // determine heigth of grid int height = line.length() / width; // add together 1 height if there's partial lastly row if (line.length() % width != 0) height += 1; loadunloadgrid(line, width, height); } } static void loadunloadgrid(string line, int width, int height) { char grid[][] = new char[height][width]; // determine number long columns int longcolumn = line.length() % width; if (longcolumn == 0) longcolumn = width; //load input info grid column int charcount = 0; (int c = 0; c < width; c++) { (int r = 0; r < height; r++) { if (r < height - 1 || c < longcolumn) { grid[r][c] = line.charat(charcount); charcount += 1; } } } // output info grid rows (int r = 0; r < height - 1; r++) { (int c = 0; c < width; c++) { system.out.print(grid[r][c]); } } // special handling lastly row (int c = 0; c < longcolumn; c++) { system.out.print(grid[height - 1][c]); } system.out.println("\""); } }

if text file has abcde, abcde. characters in grid determined min , max width.

if understand correctly want abcdefg into

b c d e f g

but in fragment writing on screen miss new line character

// output info grid rows (int r = 0; r < height - 1; r++) { (int c = 0; c < width; c++) { system.out.print(grid[r][c]); } }

should

// output info grid rows (int r = 0; r < height - 1; r++) { (int c = 0; c < width; c++) { system.out.print(grid[r][c]); } system.out.println(); }

java multidimensional-array

No comments:

Post a Comment