0

Suppose we are giving run time value of n and we want to print the n number of stars in a single row without making use loop and/or condition. How we can do it in java?

2 Answers2

2

Well, here is a neat little trick you could use.

System.out.println(new String(new char[n]).replace("\0", "*"));

Credit for that little snippet goes to user102008 in this thread...

Essentially you are creating a new string using a new char array with [n] indexes. When you create a new array without specifying values, default values are given. The default char is '\0' (the null character). So, by using replace() on the created string you can replace all instances of that character (the number of which you have already specified) with whatever char/String you like.

Community
  • 1
  • 1
Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77
  • 3
    What's the point of answering by copying from a duplicate? – s.bandara Mar 06 '14 at 18:24
  • @s.bandara - They wanted to know and they might not have found it otherwise. Would you have rated it up if I hadn't given credit to it's creator? – Rudi Kershaw Mar 06 '14 at 18:26
  • 1
    As this is likely homework related, I would downvote it either for being unhelpful to the OP or [code trolling](http://meta.codegolf.stackexchange.com/questions/746/code-troll-rules) (outside of code golf.SE). –  Mar 06 '14 at 18:39
  • @MichaelT - How exactly is that code trolling? It does exactly what they ask in one line, it's concise, fairly easy to read and has little to no overheads. By the definition you just linked it is literally the opposite of code-trolling. – Rudi Kershaw Mar 06 '14 at 18:45
  • That you @RudiKershaw i got it. – Rajnish Pandey Mar 07 '14 at 01:17
2

You can use recursion to print out stars with the following code:

public class RecursiveStars {

    public static void main(final String[] args) {
        printStar(5);
    }

    /**
     * 
     * @param i
     *            the number of stars to print
     */
    private static void printStar(final int i) {
        if (i > 0) {
            System.out.print('*');
            printStar(i - 1);
        }
    }

}

If you want to avoid the condition you can still use recursion but break out of the loop by triggering an ArithmeticException. (This is horrible, but does meet your requirement.)

public class RecursiveStars {

    public static void main(final String[] args) {
        try {
            printStar(5);
        } catch (final ArithmeticException e) {
            // Ignore
        }
    }

    /**
     * 
     * @param i
     *            the number of stars to print
     */
    private static void printStar(final int i) {
        final int triggerException = 1 / i;
        System.out.print('*');
        printStar(i - 1);
    }
}
Richard Miskin
  • 1,260
  • 7
  • 12