Align a String to the right using printf in Java

381 Views Asked by At

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

4

There are 4 best solutions below

2
rzwitserloot On

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.

0
Julian Kreuzer On

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?

0
Pran Sukh On

This could be possible with string formats.

Have a look at this link Read More.

0
htamayo On

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();
        }        
    }
}