语句的Java代码格式

时间:2014-11-18 19:07:28

标签: java for-loop formatting

他们是一种更好的格式化for-loop的方法吗?

用户输入两个初始化为x and y的整数,程序将这些值打印为+表示第一个数字和 - 表示第二个数字。

  

对于例9和5将导致

     
    

+++++++++ -----

  

我尝试使用嵌套的for-loop,但这导致了

  

+ ----- + + ----- ----- ----- + + ----- + + ----- ----- + ---- - + - - - -

    Scanner sc = new Scanner(System.in);
    int x,y,total = 0;

    System.out.println("Enter two numbers greater than 0 and no greater than 20!");
    x = sc.nextInt();
    y = sc.nextInt();

    draw(x,y);  

    private static void draw(int x, int y) {
    for(int i=1; i<=x; i++)
    {
        System.out.print("+");

    }
    for(int j=1; j<=y; j++)
    {
        System.out.print("-");
    }
}

3 个答案:

答案 0 :(得分:1)

public class MainClass {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int x, y, total = 0;

        System.out.println("Enter two numbers greater than 0 and no greater than 20!");
        x = sc.nextInt();
        y = sc.nextInt();

        draw(x, y);
    }

    private static void draw(int x, int y) {
        for (int i = 1; i <= x; i++) {
            System.out.print("+");

        }
        for (int j = 1; j <= y; j++) {
            System.out.print("-");
        }
    }

}

Enter two numbers greater than 0 and no greater than 20!

9   --> Hit enter.
5   --> Hit enter again!
+++++++++-----

答案 1 :(得分:1)

如果你想让它变小:)

private static void draw(int x, int y) {
    for (int i = -x; i < y; i++) {
        System.out.print(i<0 ? "+" : "-");
    }
}

答案 2 :(得分:1)

我会一起摆脱循环,并使用StringUtils

private static void draw(int x, int y) {
    System.out.print(Stringutils.repeat("+", x));
    System.out.println(StringUtils.repeat("-", y));
}