编写一个程序,读取与整数双向数组的顺序相对应的整数 N (0 ≤ N ≤ 100),并根据上面的示例构建数组。
输入 输入由多个整数组成,每行一个,对应于要构建的数组的顺序。输入的结束用零 (0) 表示。
输出 对于输入的每个整数,根据示例打印相应的数组。 (数组的值必须在大小为 3 的字段中右对齐并用空格分隔。数组每行的最后一个字符后不得打印空格。每个数组后必须打印一个空行.
这是我的代码。在这里我总是遇到演示错误。我知道当空间或线条不匹配时会出现演示错误。但在这里我不明白为什么会给我演示错误。
import java.util.Scanner;
import java.text.DecimalFormat;
public class FirstClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
DecimalFormat df = new DecimalFormat("0.0");
Scanner input = new Scanner(System.in);
int n;
while((n =input.nextInt())!= 0){
int newArray[][] = new int[n][n];
int hn = n/2;
if(n%2 == 1) {
hn++;
}
int a = 0;
int b = n-1;
for (int l = 1; l <= hn; l++) {
for (int i = a; i <= b; i++) {
for (int j = a; j <= b; j++) {
newArray[i][j] = l;
}
}
a++;
b--;
}
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray.length; j++) {
if (j == 0) {
System.out.print(" "+newArray[i][j]);
}else {
System.out.print(" "+newArray[i][j]);
}
}
System.out.println();
}
System.out.println();
}
}
}
最佳答案
问题出在你的打印逻辑上。尝试使用以下代码进行打印。我检查了在线判断中的代码,它可以工作!
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray.length; j++) {
if(j == 0) System.out.printf("%3d",newArray[i][j]);
else System.out.printf(" %3d",newArray[i][j]);
}
System.out.println();
}
希望这能解决您的问题。如果您有任何不明白的地方请告诉我。快乐编码!
关于java - URI在线判断1435方阵I(呈现错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60202593/