0

So, I just enrolled into a competition (Code Quest, Fl) and I am fairly amateur at programming(Started a year ago with Javascript), and I was looking at last year's competition questions, and since I have never had a good understanding of arrays I decided to try the challenge I put in the title. My code works fine, but in order to output the grid, I need to call to a pre-existing string inside the array, i.e. I can only call up to poundArry[3] right now because I only have 4 strings in the array. I need to know how to add a string with the number of "#" symbols as you type in the console. Sorry for any confusion in my code and any weird variable names.

static int gridSize;
static String pound = "#";  
static String[] poundArry = {"#","##","###","####"};
static Scanner sc = new Scanner(System.in);
public static void drawSymbols() {
    for(int i = 0; i<=gridSize;
            i++,
            System.out.println(poundArry[gridSize])
        );
}
public static void calculateGrid() {
    drawSymbols();
}
public static void main(String[] args) {
    System.out.println("Enter Grid Size");
    gridSize = sc.nextInt()-1;
    calculateGrid();
}
JakeTheSnake
  • 372
  • 1
  • 11

1 Answers1

0

The most optimal (performance/memory) way to create a String of repeated characters is:

public static String repeat(char ch, int count) {
    char[] buf = new char[count];
    java.util.Arrays.fill(buf, ch);
    return new String(buf);
}

If you're working on a bigger project, put that in a utility class, e.g. named StringUtils.

Of course, you don't actually have to write it, because it already exists in Apache Commons Lang third-party library: StringUtils.repeat(char ch, int repeat).

Or Guava's Strings.repeat(String string, int count).

Andreas
  • 154,647
  • 11
  • 152
  • 247