0

I am writing a program to display an array of char in rows and columns(see below). But, the output of my code right now is like so:

hhhhehehehelhelhelhellhellhell

What i want to display is this:

h e l l
o w o r
l d n e
w d a y

And here's my current code:

String str = "helloworldnewday"; 

  double length = Math.sqrt(str.length());
  int x = (int) length;

  char[] ch = new char[str.length()]; 

  for (int i = 0; i < x; i++) { 
    for (int j = 1; j< x; j++){
      ch[i] = str.charAt(i); 
      System.out.print(ch);
    } 
  } 

I know my code is terrible because I just began learning. Can you guys tell me what's wrong with my code? I appreciate every answer. Thank you.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80

1 Answers1

1

You only need one for loop over all the characters of the String. Use the modulus operator (%) to check if you need to print a new line. See the below code in action here.

String str = "helloworldnewday";
double length = Math.sqrt(str.length());
int x = (int) length;
for (int i = 0, len = str.length(); i < len; i++) {
    System.out.print(str.charAt(i) + " ");
    if (i % x == x - 1) {
        System.out.println();
    }
}

Output:

h e l l 
o w o r 
l d n e 
w d a y 
Unmitigated
  • 76,500
  • 11
  • 62
  • 80