Java 如何将阵列从单线更改为20x20正方形?(爪哇)
我需要更改数组的格式,使其显示为20x20正方形。有什么好办法可以做到这一点吗Java 如何将阵列从单线更改为20x20正方形?(爪哇),java,Java,我需要更改数组的格式,使其显示为20x20正方形。有什么好办法可以做到这一点吗 public class MyGrid { public static void main(String[] args) throws IOException { FileReader file = new FileReader("list.txt"); int[] integers = new int [400]; int i=0; try {
public class MyGrid {
public static void main(String[] args) throws IOException
{
FileReader file = new FileReader("list.txt");
int[] integers = new int [400];
int i=0;
try {
Scanner input = new Scanner(file);
while(input.hasNext())
{
integers[i] = input.nextInt();
i++;
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(Arrays.toString(integers));
}
}对我来说,最简单、最快的方法是:
public class MyGrid {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("list.txt");
int[] integers = new int[400];
int[][] table = new int[20][20];
int m, n, i = 0;
int tableWidth = table[0].length; // 20 in that case
try {
Scanner input = new Scanner(file);
while(input.hasNext()) {
int value = input.nextInt();
integers[i] = value;
m = i / tableWidth; // Row index
n = i % tableWidth; // Column index
table[m][n] = value;
i++;
}
input.close();
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(integers));
}
}
此外,此代码将适应任何其他表格大小(例如500、600或4237个元素)
注意:此代码将以2D数组存储数据,但不会在控制台中显示。如果您想在读取文件时显示数据,我建议您查看@Elliott-Frisch更适合的答案;我建议利用它来安全地清理。我看不出有任何必要用你的扫描仪安装文件阅读器(文件就足够了)。然后每20个值打印一个换行符,否则打印一个空格;然后打印值。像
int[] integers = new int[400];
try (Scanner input = new Scanner(new File("list.txt"))) {
int i = 0;
while (input.hasNextInt()) {
integers[i] = input.nextInt();
if (i != 0) {
if (i % 20 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
System.out.printf("%03d", integers[i]);
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
是的,但这是我在java中尝试的第一个程序,所以我对任何东西都是新手。看看这个答案,当我尝试这个解决方案时,它仍然像普通方式一样打印数组,而不是用20x20方法。不错,但我读到的问题是如何以20x20正方形输出。您需要替换普通的System.out.println来完成此操作。是的,您是对的,我的代码创建了一个20x20表,但之后您必须显示它,所以我是个傻瓜,忘记导入“import.java.io.File”;但感谢您的帮助!