英文:
Java Loop Number square ( reversed order ) each line
问题
我在思考如何制作这个...
我在互联网上找到了以下代码,它可以生成一个数字方阵模式
```java
import java.util.Scanner;
public class Square {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a;
System.out.print("输入:");
a = sc.nextInt();
for (int iOuter = 1; iOuter <= a; iOuter++) {
for (int i = 1; i <= a; i++) {
System.out.print(i);
}
System.out.println();
}
}
}
如果我输入5,输出将会是这样的:
12345
12345
12345
12345
12345
我想要的输出是:
12345
54321
12345
54321
12345
提前感谢您的帮助
<details>
<summary>英文:</summary>
So i was wondering about how do i make this...
i found this code on the internet that gives me a number-square pattern
import java.util.Scanner;
public class Square {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a;
System.out.print("Input :");
a = sc.nextInt();
for (int iOuter = 1; iOuter <= a; iOuter++) {
for (int i = 1; i <= a; i++) {
System.out.print(i);
}
System.out.println();
}
}
}
this is the output if i put in 5
12345
12345
12345
12345
12345
im looking for this output
12345
54321
12345
54321
12345
Thanks in advance
</details>
# 答案1
**得分**: 0
尝试一下这段代码:
```java
for (int iOuter = 1; iOuter <= a; iOuter++) {
for (int i = 1; i <= a; i++) {
if (iOuter % 2 == 0) { // 如果是偶数行
System.out.print(1 + a - i);
} else { // 如果是奇数行
System.out.print(i);
}
}
System.out.println();
}
这将在奇数行和偶数行上产生不同的结果。
英文:
Try this code:
for (int iOuter = 1; iOuter <= a; iOuter++) {
for (int i = 1; i <= a; i++) {
if (iOuter % 2 == 0) { // if is even
System.out.print(1 + a - i);
}else {// if is odd
System.out.print(i);
}
}
System.out.println();
}
This will make diifferent things for odd and even rows.
答案2
得分: 0
这只是将值转换为字符串,然后使用StringBuilder进行反转。
int val = 54321;
StringBuilder sb = new StringBuilder().append(val);
for(int i = 0; i < 5; i++) {
System.out.println(sb.reverse());
}
输出
12345
54321
12345
54321
12345
<details>
<summary>英文:</summary>
This simply converts the value to a String and uses StringBuilder to reverse it.
int val = 54321;
StringBuilder sb = new StringBuilder().append(val);
for(int i = 0; i < 5; i++) {
System.out.println(sb.reverse());
}
Prints
12345
54321
12345
54321
12345
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论