1

I need to right justify the next output using Java:

class MyTree {

    public static void staircase(int n) {
        String myGraph = "#";
        for(int i=0; i<n; i++){
            for(int x = 0; x <=i; x++){
                if(x == i){
                    System.out.printf("%s\n", myGraph);
                }else{
                    System.out.printf("%s", myGraph);                    
                }
            }
        }
    }
}

I'm using printf function but I'm stuck, I tried different parameters but nothing seems to work; in case you have a suggestion please let me know.

Thanks

htamayo
  • 335
  • 3
  • 16

4 Answers4

1

You can't right justify unless you know the 'length' of a line, and there's no way to know that. Not all things System.out can be connected to have such a concept.

If you know beforehand, you can use %80s for example. If you don't, what you want is impossible.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • cool, thanks for the tip, one more question: in case the length of each line is determined by a variable, what would be a way to reference it, because something like System.out.printf(%myvars, data) didn't work, any hints? – htamayo Sep 30 '21 at 17:21
  • `int len = 80; printf("%" + len + "s");` – rzwitserloot Sep 30 '21 at 18:02
0

This is not possible, the java output stream is so abstract that you basically don't know where the data is ending which you send to it.
Case scenario:
Somebody has set the output steam to a file where would there the right alignment be there?

Julian Kreuzer
  • 358
  • 1
  • 9
0

This could be possible with string formats.

Have a look at this link Read More.

Pran Sukh
  • 207
  • 4
  • 12
0

this approach solve the problem:

class Result {
    public static void staircase(int n) {
        String myGraph = "#";
        String mySpace = " ";
        int numOfChars = 0;
        int i = 0;
        int j = 0;
        int k = 0;
        ArrayList<ArrayList<String>> gameBoard = new ArrayList<ArrayList<String>>();
        for(i=0; i<n; i++){
            gameBoard.add(new ArrayList<String>());
            numOfChars++;
            //fill of mySpace
            for(j=0; j<(n-numOfChars); j++){
                gameBoard.get(i).add(j, mySpace);
            }
            //fill of myGraph
            for(k=j; k<n; k++){
                gameBoard.get(i).add(k, myGraph);
            }
        }
        
        //iterate the list
        for (i = 0; i < gameBoard.size(); i++){
            for (j = 0; j < gameBoard.get(i).size(); j++){
                System.out.print(gameBoard.get(i).get(j));
            } 
            System.out.println();
        }        
    }
}
htamayo
  • 335
  • 3
  • 16