0

So i am trying to make this board of 10 rows and 10 columns. I have to used the StringBuilder method to make it but I am unable to do so. My output is coming out wrong. Here is my code

import java.util.ArrayList;
import java.util.Scanner;
public class bord {
    public static void main(String[] args) {
        StringBuilder s= new StringBuilder();
        for( int r=0;r<10;r++)
        {
            for( int c=0;c<10;c++)
            {
                s.append("-");
                System.out.print(" "+s);
            }
            System.out.println("");
        }   
}
}

And here is what i want:

enter image description here

the feels
  • 107
  • 1
  • 7

4 Answers4

1

This works:

public class Board {
    public static void main(String[] args) {
    StringBuilder s= new StringBuilder();
    for( int r = 0; r < 10; r++) {
        for( int c = 0; c < 10; c++) {
            s.append("- ");
        }
        s.append("\n");
    }
    System.out.print(s);
    }
}
slal
  • 2,657
  • 18
  • 29
1

Just a another solution and in case you want to use one loop :

StringBuilder s = new StringBuilder();
for (int r = 0; r < 10; r++) {
    s.append(String.format("%0" + 10 + "d", 0).replace("0", "- "));
    s.append("\n");
}
System.out.println(s.toString());

Output

- - - - - - - - - - 
- - - - - - - - - - 
- - - - - - - - - - 
- - - - - - - - - - 
- - - - - - - - - - 
- - - - - - - - - - 
- - - - - - - - - - 
- - - - - - - - - - 
- - - - - - - - - - 
- - - - - - - - - - 
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

And don't forget those who try to use the stream API wherever possible.

StringBuilder sb = new StringBuilder();
IntStream.range(0,100).forEach(i -> { sb.append(i%10 == 9 ? "-\n" : "- ");});
System.out.println(sb.toString());

Using for-loops is so 2013 ;-P

Jan B.
  • 6,030
  • 5
  • 32
  • 53
-2

use below code :-

 public static void main(String[] args) {
        for( int r=0;r<10;r++)
        {
            StringBuilder s= new StringBuilder();

            for( int c=0;c<10;c++)
            {
                s.append("-");
            }
            System.out.print(" "+s);

            System.out.println("");
        }   
}
Anshul Sharma
  • 3,432
  • 1
  • 12
  • 17