htamayo
htamayo

Reputation: 353

Align a String to the right using printf in Java

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

Upvotes: 1

Views: 393

Answers (4)

htamayo
htamayo

Reputation: 353

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

Upvotes: 0

Pran Sukh
Pran Sukh

Reputation: 545

This could be possible with string formats.

Have a look at this link Read More.

Upvotes: 0

Julian Kreuzer
Julian Kreuzer

Reputation: 356

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?

Upvotes: 0

rzwitserloot
rzwitserloot

Reputation: 102822

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.

Upvotes: 1

Related Questions