Im really bad at programming just started recently and i was wondering how would you combine these for loops since they look the same except for the paramaters this program makes stairs. Thanks a bunch

import java.util.Scanner;

public class example {
	public static final int SUB_HEIGHT = 4;

	public static void main(String[] args) {
		drawBox();

		System.out.println();
	}

	public static void drawBox() {
		int number = 1;
		int i;
		int j;
		int k;

		Scanner keyboard = new Scanner(System.in);
		System.out.print("How many Rows? ");
		int drawbox = keyboard.nextInt();

		
		
		for (i = 1; i <= drawbox; i++) {

			for (j = 1; j <= i; j++) {

				System.out.print("+---");

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

			}
			for (k = 1; k <= number; k++) {
				System.out.print("+");
			}

			System.out.println();

			for (j = 1; j <= i; j++) {

				System.out.print("|   ");

			}

			for (k = 1; k <= number; k++) {
				System.out.print("|");
			}

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

		for (k = 1; k <= number; k++) {
			System.out.print("+");

		}
	}
}

you see half of the code is pretty much identical except for parameters how to you combine them

Not so bad on programming since you spotted pattern of similarity, you can simplify it as follows

public void printPattern(String pattern, int maxIteration){
    for (j = 1; j <= maxIteration; j++) {
        System.out.print(pattern);
    }
}

and then in for loop

for (i = 1; i <= drawbox; i++) {
   printPattern("+---",i);
   printPattern("", i);
}

Even above can be simplified. Can you think of any way to organize all this string patterns and be able to simple to iterate through them?
Hint, collection and classes implementing this interface

Consider...
What does this code do:

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

(Hint: What would happen if we just deleted it? ;-)

Also, notice that number always has the value one. So this code could be simplified:

for (k = 1; k <= number; k++) {
				System.out.print("+");
			}
			System.out.println();

Then I would probably do something like what peter budo suggested above, except that I would pass in two String parameters, along with the one int parameter.

My end result looks kind of like this:

for (int i = 1; i <= drawbox; ++i) {
			printPattern(…, i);
			printPattern(…, i);
		}
		printPattern(…, drawbox);

Where I've used the "…" character to hide the two String parameters I suggested above. ;->

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.