Java AsciiArt无法正确打印

时间:2013-09-28 21:37:38

标签: java ascii

import java.util.Scanner;
public class asciiart {
    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

        int number1 = input.nextInt();
        int number2 = input.nextInt();
        input.close();

        if ((number1 < 3) && (number2 <3)) {
            System.out.println("Error: both rows and columns less than 3");
            System.exit(0);
        }
        else if (number2 <3) {
            System.out.println("Error: columns less than 3");
            System.exit(0);
        }
        else if (number1 < 3) {
            System.out.println("Error: rows less than 3");
            System.exit(0);
        }
        else {
            asciiArt(number1, number2);
        }
    }


    public static void asciiArt(int columns, int rows) {
        int dotLength = 0;
        int xLength = 0;
        int halfLength = 0;

        if ((rows < columns) && (rows % 2 != 0)) {
            dotLength = (rows - 1) / 2;
            xLength = columns - (dotLength * 2);
            halfLength = (rows / 2) + 1;
        }
        else if ((columns < rows) && (columns % 2 != 0)) {
            dotLength = (columns - 1) / 2;
            xLength = 1;
            halfLength = (rows / 2) + 1;
        }
        else if ((rows < columns) && (rows % 2 == 0)) {
            dotLength = (rows - 2) / 2;
            xLength = columns - (dotLength * 2);
            halfLength = (rows / 2) + 1;
        }
        else if ((columns < rows) && (columns % 2 == 0)) {
            dotLength = (columns - 2) / 2;
            xLength = 2;
            halfLength = (rows / 2) + 1;
        }
        else if ((columns == rows) && (columns %2 == 0)) {
            dotLength = (rows - 2) / 2;
            xLength = columns - (dotLength * 2);
            halfLength = (rows / 2);
        }
        else if ((columns == rows) && (rows % 2 != 0)) {
            dotLength = (rows - 1) / 2;
            xLength = columns - (dotLength * 2);
            halfLength = (rows / 2) + 1;
        }

        for(int x = 0; x < rows; x++) {
            for(int z = 0; z < dotLength; z++) {
                System.out.print(".");
            }
            for(int a = 0; a < xLength; a++) {
                System.out.print("x");
            }
            for(int b = 0; b < dotLength; b++) {
                System.out.print(".");
            }

            if (x > (halfLength - 2)) {
                dotLength = dotLength + 2;
                xLength = xLength - 4;
            }

            System.out.println("");
            dotLength = dotLength - 1;
            xLength = xLength + 2;
        }
    }
}

具有均匀尺寸的正方形的输入不会向右或具有不同的尺寸。

问题示例:

6x6平方显示为:

..xx..
.xxxx.
xxxxxx
.xxxx.
..xx..
......

4x7看起来像:

.xx.
xxxx
xxxxxx
xxxxxxxx
xxxxxx
xxxx
.xx.

当列大于行(例如:6x5,9x6 ...)和奇数边的正方形时,它可以正常工作。

9×7

...xxx...
..xxxxx..
.xxxxxxx.
xxxxxxxxx
.xxxxxxx.
..xxxxx..
...xxx...

5×5

..x..
.xxx.
xxxxx
.xxx.
..x..

0 个答案:

没有答案