this is one of the interview question. I am supposed to print multiple lines of output on command line, without using the newline(\\n
) character in java. I trie
The ASCII value of new Line is 10. So use this
char line = 10;
System.out.print("1" + line + "2" + line ......);
Probably cheating based on the requirements, but technically only 1 println statement and no loops.
public int recursivePrint(int number)
{
if (number >=5 )
return number;
else
System.out.println(recursivePrint(number++));
}
No loops, 1 println call, +flexibility:
public static void main (String[] args) {
print(5);
}
final String newLine = System.getProperty("line.separator");
public void print(int fin) {
System.out.println(printRec("",1,fin));
}
private String printRec(String s, int start, int fin) {
if(start > fin)
return s;
s += start + newLine;
return printRec(s, start+1, fin);
}
If you're just not allowed of using \n
and println()
then you can get the systems line.separator
, e.g.
String h = "Hello" + System.getProperty("line.separator") + "World!"
Hope this helped, have Fun!
You can do it recursively:
public void foo(int currNum) {
if (currNum > 5)
return;
println(currNum);
foo(currNum + 1);
}
Then you are only using a single println
and you aren't using a for or while loop.
There are many ways to achieve this...
One alternative to using '\n' is to output the byte value for the character. So, an example to print out your list of the numbers 1-5 in your example...
char line = (char)10;
System.out.println("1" + line+ "2" + line+ "3" + line + "4" + line+ "5");
You could also build a byte[] array or char[] array and output that...
char line = (char)10;
char[] output = new char[9]{'1',line,'2',line,'3',line,'4',line,'5'};
System.out.println(new String(output));