开发者

A way to print rows in a alternate directions in Java without using 2D arrays..ArrayLists, LinkedLists

for practice purposes, I'm trying to find a way to print rows of numbers开发者_如何学Python in alternate for each row

etc..

100 99 98 97 96 95 94 93 92 91

81 82 83 84 85 86 87 88 89 90

80 79 78 77 76 75 74 73......

....without the use of 2D arrays, ArrayLists, LinkedLists..

so far I've done it, but my solution to this is quite long and can be repetitive... was wondering if there's a 'shorter' way around this...

Here is what I've done...

public class PrintNumbers {

    public static void main(String args[])
    {
        PrintNumbers app = new PrintNumbers();
        app.display();
    }


    public void display()// main display
    {
        display_cell_left_to_right(100,90);
        display_cell_right_to_left(81,91);
        display_cell_left_to_right(80,70);
        display_cell_right_to_left(61,71);
        display_cell_left_to_right(60,50);
        display_cell_right_to_left(41,51);
        display_cell_left_to_right(40,30);
        display_cell_right_to_left(21,31);
        display_cell_left_to_right(20,10);
        display_cell_right_to_left(1,11);
        board_displayLine();


    }//end display method

    public void board_displayLine(){
        System.out.println("");
        for (int i = 10; i > 0; i--)
            System.out.print("+-------");

        System.out.print("+");
        System.out.println("");
    }//end board_displayLine

    //method to display cells from left to right according to a range of indexes
    public void display_cell_left_to_right(int max,int min){
        board_displayLine();
        for (int i = max; i > min; i--)//
            System.out.print("|"+i+"\t");
        System.out.print("|");
    }
    //same as above but vice versa
    public void display_cell_right_to_left(int min, int max){
        board_displayLine();
        for (int i = min; i < max; i++)
            System.out.print("|"+i+"\t");
        System.out.print("|");
    }

}

Thanks!


Here's my version that's meant for humans:

public static void main(String[] args) {
    int ROWS = 10;
    int MAX = 100;
    int currentValue = MAX;
    for(int i = 0; i < ROWS; i++) {
        if (i % 2 == 0) {
            for (int j = 0; j < MAX / ROWS; j++) {
                System.out.print(currentValue-- + " ");
            }
        } else {
            currentValue -= MAX / ROWS;
            for (int j = MAX / ROWS; j >= 0; j--) {
                System.out.print((currentValue + ((MAX / ROWS) - j)) + " ");
            }
            currentValue--;
        }
        System.out.println();
    }
}


Try something like this

for(int i = 9; i>=0; i--){
    boolean right = (i%2 == 0);
    for(int j = (right?1:10); j!=0 && j!=11; j = j + (right?1:-1)){
        System.out.print(i*10 + j);
        System.out.print("\t");

    }
    System.out.println();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜