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

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
int len = 80; printf("%" + len + "s");
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?

Comments

0

This could be possible with string formats.

Have a look at this link Read More.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.