1

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("-");
    }
}
2
  • 1
    What exactly are you trying to achieve? Commented Nov 18, 2014 at 19:08
  • It's for a University assignment where the first number inputted is printed out as plusses and the second number is printed as minuses. The code so far does as i wish. I'm just looking how to improve it, because nobody's code is perfect, right!? Commented Nov 18, 2014 at 19:34

3 Answers 3

1

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 ? "+" : "-");
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Place of "+","-" is reverse :) Result for x = 5, y=4 is -----++++
What actually is ? in Java.
@GrahamWarrender It's ternary operator ?:
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 Comment

Is ıt same with Graham Warrender's code in question?
1

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

1 Comment

You forgot to print it: System.out.print(StringUtils.repeat("+", x) + StringUtils.repeat("y", x));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.