从循环打印输出中删除最后一个逗号 [英] remove last comma from loop printouts JAVA

查看:170
本文介绍了从循环打印输出中删除最后一个逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在循环打印输出时遇到了一个小问题。

I got a small problem with the printouts from a loop.

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数组(行和列),然后从每个插槽中遍历另一个1D arrayList,如果arrayList中的插槽与2D数组中的插槽匹配,则打印2D数组中的列和arrayList的索引

Explaining the code: it traverses through a 2D array (row and col), then from each slot, traverses through another 1D arrayList, if that slot in arrayList matches with the slot in the 2D array, print the column from 2D array and the index of the 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个匹配项。
我尝试使用子字符串,在网上找到了一些正则表达式,但是它们不起作用

b 1 and c 2 are on the same line because there are 2 matches in one row. I only need the comma to separate between 2 matches within one row. I have tried using substring, some regex found online but they didn't work

此外,我想在最后两行显示无 (状态7和8)。我也一直在尝试这样做,但还是没有运气。

In additional, I want to display "none" for the last 2 rows (state 7 and 8). I have been also trying to do it but still no luck.

请提供一些建议,谢谢

推荐答案

尝试使用:

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

这篇关于从循环打印输出中删除最后一个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆