简单的 Java 循环问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3748763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Java Loop Question
提问by bitmoe
Assume that the int variables i and j have been declared, and that n has been declared and initialized.
假设已经声明了 int 变量 i 和 j,并且已经声明并初始化了 n。
Using for loops (you may need more than one), write code that will cause a triangle of asterisks of size n to be output to the screen.
使用 for 循环(您可能需要多个),编写将导致大小为 n 的星号三角形输出到屏幕的代码。
For example, if the value of n is 4, the output should be
例如,如果 n 的值为 4,则输出应为
*
**
***
****
回答by Michael Aaron Safyan
I won't do your homework, so here is a hint:
我不会做你的作业,所以这里有一个提示:
- The first line is always 1 element long.
- The last line is always N elements long.
- The are a total of N lines.
- 第一行总是 1 个元素长。
- 最后一行总是 N 个元素长。
- 一共有N行。
Surely, with the above, you can create the necessary program.
当然,有了以上内容,您就可以创建必要的程序了。
回答by Andreas Dolk
Just for fun - single for-loop solution:
只是为了好玩 - 单个 for 循环解决方案:
public void doIt(int n) {
String temp = String.copyValueOf(char[n]);
for (int i = 1; i <= n; i++)
System.out.println(temp.substring(n-i).replace((char) 0, 'x'));
}
And some recursion - zero for-loop solution:
还有一些递归 - 零 for 循环解决方案:
public void doItAgain(int n, String display) {
if (n==0) return;
System.out.println(display);
doItAgain(n-1, display+'x');
}
(call it with doItAgain(4,"x")
for your example)
(doItAgain(4,"x")
以您的示例调用它)
回答by Jimvell
My answer:
我的答案:
public class loop1
{
public static void main(String[] args)
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j <= i; j++)
System.out.print("*");
System.out.println();
}
}
}
回答by shahzad
public class ForLoop {
public static void main(String[] args) {
for(int i = 0;i <= 9;i++){
for(int j = 1;j <= i;j++){
System.out.print("*");
}
System.out.println("\n");
}
}
}
回答by Sam Day
In case you're in school/college and more interested in getting some, more power to you buddy:
如果你在学校/大学并且更想获得一些,更多的权力给你的伙伴:
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= i; j++)
System.out.print("*");
System.out.println();
}
回答by bakirov
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++)
System.out.print("*");
System.out.println();
}
回答by Valerie Schnapp
simple, easist way to do it using main method --> public static void main (Strings [] args){
使用 main 方法的简单、简单的方法 --> public static void main (Strings [] args){
for(int i = 1; i <= max; i++){
for(int j = 1; j <= i; j++){
System.out.print("*");
}
System.out.println(" ");
}
}