大家好,我需要你的帮助,这是我的代码
public class act_numTria {
public static void main(String[] args) {
int z = 9;
for(int x = 1; x <= 4; x++) {
for(int y = 4; y >= x; y--) {
System.out.print(z);
z--;
}
System.out.print("\n");
}
}
}
输出是:
9876
543
21
0
但它应该是这样的
6789
345
12
0
答案 0 :(得分:1)
如果你不想涉及任何字符串操作,你可以这样做......
public class act_numTria {
public static void main(String[] args) {
int z = 9;
for(int x=1;x<=4;x++){
for(int y=4;y>=x;y--){
System.out.print(z-y+1);
}
z = z - (4 - x);
System.out.print("\n");
}
}
}
答案 1 :(得分:0)
以下是您的修改后的代码..您只需要累积数字然后将其反转:
public class act_numTria {
public static void main(String[] args) {
int z = 9;
for (int x = 1; x <= 4; x++) {
StringBuilder sb = new StringBuilder();
for (int y = 4; y >= x; y--) {
sb.append(z--);
}
System.out.print(sb.reverse().toString() + "\n");
}
}
}
以下是您问题的另一种解决方案:
public class act_numTria {
public static void main(String[] args) {
int start = 6;
int diff = 3;
for (int z = start; diff>=0; z=start) {
for(int i=z;i<=start+diff;i++) {
System.out.print(i);
}
System.out.println();
start-=diff;
diff--;
}
}
}