本文介绍了在java中打印多行输出而不使用新行字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是面试问题之一。我应该在命令行上打印多行输出,而不使用java中的换行符( \ n
)。我试着谷歌搜索,没有找到合适的答案。如果我打印5个数字,则应按以下方式打印。但我不应该使用换行符也不应该循环。我必须使用单 println()
语句进行打印。你能给我一些想法吗?谢谢! 1
2
3
4
5
解决方案
你可以递归地执行:
public void foo(int currNum){
if(currNum> 5)
return;
println(currNum);
foo(currNum + 1);
}
然后你只使用一个 println
并且您没有使用for或while循环。
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 tried googling for this, didn't find appropriate answers. If i am printing 5 numbers, then it should print in the following fashion. But I am not supposed to use the newline character nor loops either. I have to print this using a single println()
statement. Can you give me some ideas ? Thanks !
1
2
3
4
5
解决方案
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.
这篇关于在java中打印多行输出而不使用新行字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!