将2D数组中的字符串打印为一定数量的行

时间:2016-04-25 00:30:33

标签: java

我试图用Java创建一个键盘,用来输入用户输入的字母,以及每行所需的字符数。然后应该以所需的行数打印字符,因此如果输入"abcdefgh"并且所需的行号为4,则应打印:

abcd  
efgh  

但我仍然坚持如何让它发挥作用。

public class Keypad {

char [][] letters; 

public Keypad(String chars, int rowLength) {
    int counter = 0; 
    for (int i = 0; i<chars.length(); i++){
        counter++; 
    }
    letters = new char[rowLength][counter/rowLength];  
}

public String toString() {
    String s = " "; 

    for (int row=0; row<letters.length; row=row+1) { // Over rows
        for (int col=0; col<letters[row].length; col=col+1) {  
            s = s + letters[row][col];
        }
        s = s + "\n";
    }
    return "the keypad is" + s; 
}

1 个答案:

答案 0 :(得分:3)

toString()方法的逻辑看起来很好,但是你没有在构造函数中填充letters数组。所以你需要在构造函数中添加这样的东西:

    public Keypad(String chars, int rowLength) {
        // you don't need to count the length with a loop
        int nRow = chars.length()/rowLength;
        if(chars.length()%rowLength!=0) nRow++;
        letters = new char[nRow][rowLength];

        for(int i = 0, n = 0 ; i < letters.length ; i++) {
            for(int j = 0 ; n < chars.length() && j < letters[i].length ; j++, n++) {
                letters[i][j] = chars.charAt(n);
            }
        }
    }