使用一个参数绘制十字的方法

时间:2014-11-11 18:40:01

标签: java loops methods

所以我需要使用一个带有一个参数的方法来绘制一个大小由该参数决定的十字。所以drawCross(5)将是:

  *
  *
*****
  *
  *

我似乎无法让它发挥作用。我的代码会询问一个数字,但之后什么都没有。我敢肯定,这可能只是我愚蠢,但我不能为我的生活弄清楚它是什么。这就是我所拥有的:

import java.util.Scanner;

public class Lab9E1CrossTest {
    public static void main(String[] args) {
        Scanner kbd = new Scanner(System.in);
        System.out.print("Number: ");
        int n = kbd.nextInt();

        drawCross(n);

        kbd.close();
    }

    public static void drawCross(int n) {
        int lineCounter = 1, charCounter = 1;
        if (n % 2 == 1) {
            while (lineCounter <= n) {
                if (lineCounter == ((n / 2) + 1)) { // determines if middle line
                                                    // by dividing n by two then
                                                    // adding 1 (ex. middle of 5
                                                    // is 3, so 5/2=2, +1=3)
                    charCounter = 1;
                    while (charCounter <= n) { // prints out n number of stars
                                               // on one line
                        System.out.print("*");
                        charCounter++;
                    }
                } else {
                    charCounter = 1;
                    while (lineCounter != ((n / 2) + 1)) {
                        if (charCounter == ((n / 2) + 1)) { // if middle char of
                                                            // line
                            System.out.print("*");
                        } else {
                            System.out.print(" ");
                        }
                        charCounter++;
                    }
                }
                System.out.println(); // makes sure prints on new line
                lineCounter++;
            }
        } else {
            System.out.println("Error: Number is even.");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我首先会在您收到用户输入时验证用户输入(例如,在您致电drawCross之前确保用户输入)。

public static void main(String[] args) {
    Scanner kbd = new Scanner(System.in);
    System.out.print("Number: ");
    if (kbd.hasNextInt()) {
        int n = kbd.nextInt();
        if (n % 2 != 0) {
            drawCross(n);
        } else {
            System.out.printf("Please enter an odd #, %d is even%n", n);
        }
    }
}

接下来,我建议您创建一个实用程序方法来重复特定字符n次。然后,您可以使用重复的String(s)

绘制十字架
private static String repeat(char ch, int n) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; i++) {
        sb.append(ch);
    }
    return sb.toString();
}

类似的东西,

public static void drawCross(int n) {
    int mid = (n / 2);
    String spaces = repeat(' ', mid);
    for (int i = 0; i < mid; i++) {
        System.out.println(spaces + '*');
    }
    System.out.println(repeat('*', n));
    for (int i = 0; i < mid; i++) {
        System.out.println(spaces + '*');
    }
}