java - Print out a string of characters from a 2D array into a certain number of rows -
i'm trying make keypad in java takes letters input user, desired number of characters per row. should print characters in desired number of rows, if "abcdefgh"
input , desired row number 4 should print:
abcd efgh
but i'm stuck on how work.
public class keypad { char [][] letters; public keypad(string chars, int rowlength) { int counter = 0; (int = 0; i<chars.length(); i++){ counter++; } letters = new char[rowlength][counter/rowlength]; } public string tostring() { string s = " "; (int row=0; row<letters.length; row=row+1) { // on rows (int col=0; col<letters[row].length; col=col+1) { s = s + letters[row][col]; } s = s + "\n"; } return "the keypad is" + s; }
the logic of tostring()
method looks fine, didn't populate letters
array in constructor. need add in constructor:
public keypad(string chars, int rowlength) { // don't need count length loop int nrow = chars.length()/rowlength; if(chars.length()%rowlength!=0) nrow++; letters = new char[nrow][rowlength]; for(int = 0, n = 0 ; < letters.length ; i++) { for(int j = 0 ; n < chars.length() && j < letters[i].length ; j++, n++) { letters[i][j] = chars.charat(n); } } }
Comments
Post a Comment