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

时间:2013-08-18 09:14:18

标签: java comma

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

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数组中打印列和arrayList的索引

示例输出:

    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行显示“none”(状态7和8)。我一直在尝试这样做,但仍然没有运气。

请提出一些建议,谢谢

3 个答案:

答案 0 :(得分:1)

尝试:

String str1 = null; 
for (int row=0; row<dfsa.length; row++) {

    System.out.print("\tstate " + row +": ");   
    String line = "";
    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 + ", ";
                line += str1;
            }
        }                   
    }    
    line = line.length() > 0 ? line.substring(0, line.length() - 2) : "None";
    System.out.println(line)       
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

你可以使用

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