Remove trailing comma Java without a string variab

2019-09-21 01:57发布

public static void printGrid(int rows, int cols) {
    int totalNum = rows * cols;
    for (int i = 1; i <= rows; i++) {
        for (int k = 0; k < cols; k++) {
            System.out.print(i + rows * k + ", ");
        } System.out.println();      
    }
}

Outputs = 1, 4, 7, 10, 13, 16, 
          2, 5, 8, 11, 14, 17, 
          3, 6, 9, 12, 15, 18, 

I want to remove the trailing commas by the last numbers in each line, but I do not have a variable as a string holding them, just a print statement. Is there any way to do this?

3条回答
叛逆
2楼-- · 2019-09-21 02:28

Efficiency doesn't matter if your code is hard to understand. Part of the problem revolves around the way you are attempting to combine string composition with output. You should seperate those things entirely:

static void printGrid(int rows, int cols) {
    System.out.println(getGrid(rows, cols));
}

static String getGrid(int rows, int cols) {
    StringBuilder b = new StringBuilder();
    int totalNum = rows * cols;

    for (int i = 1; i <= rows; i++) {
        for (int k = 0; k < cols; k++) {
            b.append(i + rows * k).append(", ");
        }
        b.delete(b.size()-2,b.size());
        b.append('\n');  
    }
    return b.toString();
}

Alterantely, you could use the Guava Joiner, or in Java 8 you could use Collectors.joining

查看更多
混吃等死
3楼-- · 2019-09-21 02:44

Simply, print it only when needed:

public static void printGrid(int rows, int cols) {
    int totalNum = rows * cols;
    for (int i = 1; i <= rows; i++) {
        for (int k = 0; k < cols; k++) {
            System.out.print(i + rows * k);
            if (k < cols - 1) System.out.print(", ");
        }
        System.out.println();      
    }
}

Output for args 3, 6 would be:

1, 4, 7, 10, 13, 16
2, 5, 8, 11, 14, 17
3, 6, 9, 12, 15, 18
查看更多
倾城 Initia
4楼-- · 2019-09-21 02:46

While you might test after you print in a post-condition as suggested by @MightyPork in that answer

System.out.print(i + rows * k);
if (k < cols - 1) {
    System.out.print(", ");
}

I would test that k is not 0 and print the comma when it isn't in a pre-condition like

if (k != 0) {
    System.out.print(", ");
}
System.out.print(i + rows * k);
查看更多
登录 后发表回答