Problems with printing odd lines

I have the following method, which takes the lines of a string input, adds them to a list, and then is designed to print the even lines first and then the odd lines. The problem is that it prints even lines and doesn't print odd lines. The solution looks like it would be simple, but I can't figure out what would be wrong with my if / else statements that could cause this problem.

public static void printLines(BufferedReader r, PrintWriter w) throws IOException {
    //first prints even lines then odd lines
    ArrayList<String> list = new ArrayList<String>();

    int x = 0;
    for (String line = r.readLine(); line != null; line = r.readLine()) {
        list.add(line);
        x++;
    }
    for (int i = 1; i < list.size(); i++){
        if (i%2 == 0 && x < 1){
            w.println(list.get(i));
            x++;
        }
        else if (i%2 == 1 && x >= 1)
        {
            w.println(list.get(i));

        }
    }
}

      

+3


source to share


2 answers


Instead of dealing with arithmetic in a loop, iterate through the loop:

for (int i = 1; i < list.size(); i+=2)
    w.println(list.get(i));
for (int i = 0; i < list.size(); i+=2)
    w.println(list.get(i));

      



I recommend that you remove the x variable and use list.size () instead

+3


source


Use @Bohemian method. But if you want to use your code, just add something else to it:



    for (int i = 1; i < list.size(); i++) {
        if (i % 2 == 0 && x < 1) {
            w.println(list.get(i));
            x++;
        } else if (i % 2 == 1 && x >= 1) {
            w.println(list.get(i));
        } else{
            i = 0;
            x = 0;
        }
    }

      

+1


source







All Articles