从循环打印输出JAVA中删除最后一个逗号

我从一个循环打印输出一个小问题。

String str1 = null; for (int row=0; row<dfsa.length; row++) { System.out.print("\tstate " + row +": "); for (int col=0; col<dfsa[row].length; col++) { for (int i=0; i<dfsa_StateList.size(); i++) { // traverse thru dfsa states list if (dfsa_StateList.get(i).equals(dfsa[row][col])) { str1 = alphabetList.get(col)+ " " + i + ", "; System.out.print(str1); } } } System.out.println(); } 

解释代码:它遍历一个2D数组(row和col),然后遍历每个槽,遍历另一个1D arrayList,如果arrayList中的那个槽与2D数组中的槽匹配,则从2D数组和索引打印列的数组列表

样本输出:

  state 0: b 1, c 2, state 1: e 3, state 2: a 4, state 3: a 5, state 4: r 6, state 5: r 7, state 6: e 8, state 7: state 8: 

b 1和c 2在同一行,因为一行中有2个匹配。 我只需要用逗号分隔一行中的2个匹配项。 我尝试过使用子字符串,在网上发现了一些正则表达式,但它们没有用

另外,我想在最后2行显示“none”(状态7和8)。 我也一直试图这样做,但仍然没有运气。

请提出一些建议,谢谢

试试:

 String str1 = null; for (int row=0; row 0 ? line.substring(0, line.length() - 2) : "None"; System.out.println(line) } 
 if (dfsa_StateList.get(i).equals(dfsa[row][col])) { str1 = alphabetList.get(col)+ " " + i + ", "; if(str1.endsWith(",")) System.out.print(str1.substring(0, str1.lastIndexOf(","))); if(str1.isEmpty()) System.out.print("None"); } else {//no match System.out.print("None"); } 

您可以使用

  for (int col = 0; col < dfsa[row].length; col++) { for (int i = 0; i < dfsa_StateList.size(); i++) { // traverse thru dfsa states list if (dfsa_StateList.get(i).equals(dfsa[row][col])) { str1 = alphabetList.get(col) + " " + i + ", "; if (str1.endsWith(",")) { int index = str1.lastIndexOf(","); str1 = str1.substring(0, index); } if(str1.trim.isEmpty()) { System.out.print("None"); } else { System.out.print(str1); } } } }