[英]Input matrices from a file
我正在嘗試從輸入文件中讀取2D矩陣。輸入文件包含一系列輸入。第一行包含矩陣。大小n。每行的下n行包含n個整數,即n * n矩陣。文件結尾為矩陣大小為零,下面是一個小樣本。
2 1 1 1 1 3 3 1 2 1 1 2 2 2 1 6 1 2 3 4 2 3 3 3 4 5 2 1 4 3 3 1 2 3 5 4 3 6 2 1 3 2 4 3 4 3 2 3 4 1 5 6 0
我編寫了以下代碼,但沒有顯示我需要的代碼。
import java.util.*;
import java.io.*;
public class trial{
public static void main(String[] args) {
try{
//System.out.println(new File("input.txt").getAbsolutePath());
Scanner input = new Scanner(new File("./input.txt"));
while (true){
int n = input.nextInt();
//System.out.println("%d",n);
if(n!=0) {
int[][] grid = new int[n][n];
while (input.hasNext()) {
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
grid[row][column] = input.nextInt();
System.out.printf(" %d ", grid[row][column]);
}
System.out.println();
}
System.out.println("Array done");
}
}
input.close();
}
}catch (FileNotFoundException e){
System.out.println("File not found");
}
}
}
代碼輸出如下,它始終生成2 * 2矩陣。
1 1
1 1
陣列完成
3 3
1 2
陣列完成
1 1
2 2
陣列完成
2 1
6 1
陣列完成
2 3
4 2
陣列完成
3 3
3 4
陣列完成
5 2
1 4
陣列完成
3 3
1 2
陣列完成
3 5
4 3
陣列完成
6 2
1 3
陣列完成
2 4
3 4
陣列完成
3 2
3 4
陣列完成
1 5
6 0
陣列完成
首先,如果用戶輸入的大小為0,您似乎想停止,但實際上並沒有這樣做,而是永遠循環。 其次,在讀取第一個矩陣后,關閉掃描儀,這不是您應該做的。 input.close()
應該在while循環之外。 嘗試這個。
try {
Scanner input = new Scanner(new File("./input.txt"));
int n;
while (input.hasNextInt() && (n = input.nextInt()) > 0) {
int[][] grid = new int[n][n];
for (int row = 0; row < n; row++) {
for (int column = 0;
column < n && input.hasNextInt(); column++) {
grid[row][column] = input.nextInt();
System.out.printf("a %d ", grid[row][column]);
}
System.out.println();
}
System.out.println("Array done");
}
input.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
在您的代碼中,您無需檢查nextInt是什么大小以及何時是matrix中的數字。 另一件事是,大小0代表您的EOF,因此您應該離開。
下面是一個工作示例:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
try{
Scanner input = new Scanner(new File("pathtofile"));
while (true){
int n = input.nextInt();
//System.out.println("%d",n);
int cont =0;
if(n!=0) {
int[][] grid = new int[n][n];
while (input.hasNext() && cont != n) {
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
grid[row][column] = input.nextInt();
System.out.printf("a %d ", grid[row][column]);
}
System.out.println();
cont++;
}
System.out.println("Array done");
}
}
else{
input.close();
break;
}
}
}catch (FileNotFoundException e){
System.out.println("File not found");
}
}}
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.