Remove trailing comma Java without a string variable?

若如初见. 提交于 2019-12-13 08:23:42

问题


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?


回答1:


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



回答2:


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);



回答3:


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



来源:https://stackoverflow.com/questions/27870291/remove-trailing-comma-java-without-a-string-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!