Graham Warrender
Graham Warrender

Reputation: 365

Java Code formatting for statment

Is their a better way to format this for-loop?

The user enters two integers which are initialised to x and y the program prints these values out as + for the first number and - for the second number.

FOR EXAMPLE 9 and 5 would result in

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

I tried using a nested for-loop, but this resulted in

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

    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("-");
    }
}

Upvotes: 1

Views: 79

Answers (3)

Isaac
Isaac

Reputation: 2721

I would get rid of the loops all together, and use StringUtils.

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

Upvotes: 1

Ruslan Ostafiichuk
Ruslan Ostafiichuk

Reputation: 4702

If you want to make it smaller :)

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

Upvotes: 1

Mohammad Najar
Mohammad Najar

Reputation: 2009

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!
+++++++++-----

Upvotes: 1

Related Questions