[英]Drawing a grid using nested loops
I am trying to draw a grid that looks like this: 我正在尝试绘制一个看起来像这样的网格:
1 1
12 12
123 123
1234 1234
12345 12345
123456 123456
1234567 1234567
12345678 12345678
123456789 123456789
Here is my code: 这是我的代码:
public class shape {
public static void main(String[] args){
int number = 1, newNumber, zMax = 1;
String numString = "1";
for (int i = 1; i <= 9; i++){
for (int z = 0; z < zMax; z++){
System.out.print(numString);
number = number + 1;
numString += Integer.toString(number);
}
System.out.println("");
if (zMax <= 9)
zMax++;
}
}
}
It prints out something like this: 它输出如下内容:
1 1
12123 12123
121231234 121231234
12123123412345 12123123412345
etc 等等
It is on the right track but I can't figure out what is going wrong... please help! 这是在正确的轨道上,但我不知道出了什么问题...请帮助!
EDIT: Miss-understood the question, corrected it. 编辑:小姐理解问题,更正了它。
The reason your numbers repeat is your second loop. 您的数字重复的原因是您的第二个循环。 you either need to reinitialize numstring or reuse the old one and only add the new number.
您要么需要重新初始化numstring,要么重用旧的numstring,而仅添加新的数字。
public class shape { public static void main(String[] args){
String numString = "";
for (int i = 1; i <= 9; i++){
numstring = numstring + i;
System.out.println(numstring);
}
}
int start = 1;
int max = 10;
for(int i = 1; i < max; i++){
for(int j = 1; j <= i; j++){
System.out.print(j);
}
System.out.println("");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.