0

我从循环的打印输出中遇到了一个小问题。

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

解释代码:它遍历一个二维数组(行和列),然后从每个插槽,遍历另一个一维数组列表,如果数组列表中的插槽与二维数组中的插槽匹配,则打印二维数组中的列和索引数组列表的

样本输出:

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

请给点建议,谢谢

4

3 回答 3

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)       
}
于 2013-08-18T09:52:31.633 回答
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");
 }
于 2013-08-18T09:19:28.287 回答
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);
                }
            }
        }
    }
于 2013-08-18T09:20:39.187 回答