无法完美对齐星形

时间:2019-07-18 15:37:14

标签: java for-loop printing

我设法打印出星形,但无法精确对齐。

我知道有时它不会中断,因为某些输入将是一个奇数。但是我在左右之间得到的区别似乎是随机的...

任何帮助将不胜感激! 我已经尝试过,但是找不到合适的比例尺值,现在让我头疼。

import java.util.Scanner;

public class star {
public static void main(String[] args) {
    System.out.println("Enter a number : ");
    Scanner inp = new Scanner(System.in);
    int n = (inp.nextInt());
    int number = n;
    if (number%2 !=0)
        number++;


    // At least int over 20.
    // 3 strikes out
    int error = 0; 
    while (number < 20) {
        System.out.println("INT over 20.");
        System.out.println("3 strike out.");
        number = (inp.nextInt());
        error++;
        if (error >= 1 && number < 20) {
            System.out.println("Warning!" + error + "errors!!");
            if (error == 3)
                System.exit(-1);
            continue;
        }

    }

    int line = 0; 
    int space = 0; 
    int word = 0; 



//this loop is used to move the entire star shape by 5 spaces.
        // for(int moveparr = 0; moveparr <= 5; moveparr++)
        //  System.out.print(" ");


// top triangle

    for (line = 0; line <= (number / 4); line += 2) {
        for(int moveparr = 0; moveparr <= 5; moveparr++)
            System.out.print(" ");

        for (space = 0; (space + line) <= number; space += 2) {
            System.out.print(" ");
        }

        for (word = 0; word <= line; word++) {
            System.out.print("1");
        }
        linea++;
        System.out.println();
    }

// mid trapezoid

    for (; line >= (number / 8); line -= 2) {
        for(int moveparr = 0; moveparr <= 5; moveparr++)
            System.out.print(" ");
        for (space = 0; (space + line) <= number/4; space+=2 ) {
            System.out.print("    ");
        }
        for (word = 0; word <= 4 * line; word += 1) {
            System.out.print("2");

        }

        lineb++;
        System.out.println();

    }

//bottom 

    for (line = (number / 4); line >= 0; line -= 2) {
        for(int moveparr = 0; moveparr <= 5; moveparr++)
            System.out.print(" ");

        // bottom left
        for (space = 0; space + line >= 0; space--) {
            System.out.print(" ");
        }
        for (word = 0; word <= line; word++) {
            System.out.print("3");

        }

        // bottom right
        for (space = (line); (space + line) <= number / 2; space++) {

            System.out.print("  ");
        }

        for (word = 0; word <= line; word++) {
            System.out.print("4");

        }
        linec++;
        System.out.println();
    }

    System.out.println();
    System.out.println(number + " Input.");
    System.out.println(linea + lineb + linec + " lines printed.");
    inp.close();

}

}

0 个答案:

没有答案