2015-01-09 62 views
-1
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, 

我想刪除每行最後一個數字的尾部逗號,但我沒有一個變量作爲一個字符串來保存它們,只是一個打印語句。有沒有辦法做到這一點?刪除尾隨逗號沒有字符串變量的Java?

+7

而不是試圖將其刪除,你怎麼樣只是避免增加呢? – 2015-01-09 22:29:22

回答

8

簡單,只在需要時打印:

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

輸出爲ARGS 3,6是:

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

這不會在第一行和第二行末尾打印逗號 – 2015-01-09 22:34:13

+0

Desolator,停止傳播謊言。我甚至在Eclipse中嘗試過,以證明你錯了。我的解決方案正常。 – MightyPork 2015-01-09 22:35:52

+2

@MightyPork我猜Desolator誤解了這個問題,並認爲OP只希望刪除最後一個逗號(在你的例子中是'18')。 – Tom 2015-01-09 22:41:50

1

雖然你可能會測試你在一個後置條件打印後通過的建議@MightyPorkanswer

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

我會測試k是不是0和打印逗號時,它不是一個先決條件一樣

if (k != 0) { 
    System.out.print(", "); 
} 
System.out.print(i + rows * k); 
+0

這確實會起作用,但是哪種方式更好?沒有選擇它,真的很好奇。 – MightyPork 2015-01-09 22:51:04

+0

@MightyPork它不需要在每次迭代時計算'cols-1'。但我想這沒什麼關係。順便說一句:你們怎麼看'if(k> 0)'?更好? – Tom 2015-01-09 22:54:04

+0

這不是更好,因爲他們從根本上做同樣的事情。但我更喜歡可讀性的前提條件,只是看法。這是說我不希望第一個字符是'',而不是我最後一個字符不是','。 – 2015-01-09 22:54:15

-1

效率並不重要,如果你的代碼是很難理解。部分問題圍繞着您嘗試將字符串組合與輸出組合的方式展開。你應該完全獨立的那些事:

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,您可以使用番石榴Joiner,或在Java中8,你可以使用Collectors.joining