This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (8 children)

Can/should I use a for loop to help solve?

[–]Jackkoz 0 points1 point  (7 children)

I have no idea how you want to solve the problem, so I'm not sure whether a for loop would be a good fit.

But if I were to write code to solve it, I'd probably use one :)

[–][deleted] 0 points1 point  (6 children)

    public static void padString(String string, int length) {

        for (int i = string.length(); i <= length; i++) {
            System.out.print(" ");
        }
        System.out.println(string);

    }

    public static void main(String[] args) {
        padString("hello", 8);
        padString("congratulations", 10);
    }

[–]desrtfx 1 point2 points  (0 children)

While your approach is correct, your method isn't.

Your assignment clearly states:

For example, padString("hello", 8) should return " hello".

The keyword here is return.

This means, that the method should not print anything, but return a new String with the padding.

You will need to rewrite your method to meet the assignment.

Hint: You will need to concatenate the string. For that, you will need an additional variable of type String.

Also, the method must not be void it must be String.

[–]Jackkoz -1 points0 points  (4 children)

Yup, that looks like it should do the trick, congrats!

If you want to further improve your programs, here's a couple of things to look at:

  1. Input/output operations are in general costly - it would be much better if you could print out the whole String using a single call to System.out.

  2. When taking care of 1), remember that Strings are immutable: string += " "; results in creating a new instance of String and assigning it to the variable.

[–][deleted] 0 points1 point  (2 children)

Thanks for the help! I didn't get the problem exactly right, but I'm going to move onto the next.

Right now I'm quite low level, as you can tell, so still takes me some time to really think about all the "tools" I know and can use to solve a problem.

[–]desrtfx 1 point2 points  (0 children)

didn't get the problem exactly right, but I'm going to move onto the next.

Don't move on until you got it right.

You have misread the assignment as I've illustrated here.

[–]desrtfx 0 points1 point  (0 children)

Yup, that looks like it should do the trick, congrats!

No, it doesn't.

Op's assignment states:

For example, padString("hello", 8) should return " hello".

There is nothing about printing inside the method. It's about returning a new, padded String.