Reputation: 1723
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();
}
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
Sample output:
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 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
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.
Please give some advice, thanks
Upvotes: 0
Views: 3958
Reputation: 2789
Try with:
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)
}
Upvotes: 1
Reputation: 2243
you can use
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);
}
}
}
}
Upvotes: 0
Reputation: 7692
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");
}
Upvotes: 0