Mark Martin Mark Martin - 11 days ago 6
Java Question

Java - How to remove an extra line after "continue" in looping statement

I have tried to make an array table. But, when I add some selection followed by continue statement, it's going to be an extra line. If anyone could give suggestions to me by providing some code techniques?
This is my output:
enter image description here

public static void main(String[] args) {
String[][] table = {{"A", "B", "C", "D", "E"}, {"FirstClass", "50000", "2%", "No", "No"}, {"SecondClass", "100000", "5%", "Yes", "No"}, {"ThirdClass", "200000", "7%", "Yes", "No"}, {"FourthClass", "300000", "10%", "Yes", "Yes"}};

for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.printf("|%-15s", table[i][j]);
}
System.out.println();
}

System.out.print("\n\n");

for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if ("No".equals(table[i][3])) {
continue; //My Problem
}
System.out.printf("|%-15s", table[i][j]);
}
System.out.println();
}
}

Answer

You need to specifiy the outer loop which shall be the jump target for continue:

public static void main(String[] args) {
    String[][] table = {{"A", "B", "C", "D", "E"}, {"FirstClass", "50000", "2%", "No", "No"}, {"SecondClass", "100000", "5%", "Yes", "No"}, {"ThirdClass", "200000", "7%", "Yes", "No"}, {"FourthClass", "300000", "10%", "Yes", "Yes"}};

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            System.out.printf("|%-15s", table[i][j]);
        }
        System.out.println();
    }

    System.out.print("\n\n");

    outer:
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            if ("No".equals(table[i][3])) {
                continue outer; //note the tag
            }
            System.out.printf("|%-15s", table[i][j]);
        }
        System.out.println();
    }
}
Comments