[英]Read text file and make a 2D array
我想讀取一個文本文件並從中創建一個2D數組,但我對2D數組並不熟悉。 因此,任何幫助都非常感激我的文本文件包含所有數字。
我也嘗試了for循環,但是卻遇到了同樣的錯誤。
請在這里查看我的代碼工作量
Scanner readFile = new Scanner(new File("ELEVATIONS.txt"));
rowLength = readFile.nextInt();
colLength = readFile.nextInt();
Radius = readFile.nextInt();
int[][] data = new int[rowLength][colLength];
System.out.println("ROW : " + rowLength + " COl : " + colLength + " Radius : " + Radius );
int row = 0;
while (readFile.hasNextInt() && row < data.length) {
for (int col = 0; col < colLength; col++) {
data[row][col]= readFile.nextInt();
}
row++;
}
當我運行代碼時,它顯示以下錯誤
ROW:1000 COl:450 Radius:10數據1000450線程“主”中的異常java.util.Scanner.throwFor(Scanner.java:862)處java.util.Scanner.next(Scanner.java: 1485)在java.util.Scanner.nextInt(Scanner.java:2117)在java.util.Scanner.nextInt(Scanner.java:2076)在lab1.Lab1.main(Lab1.java:43)
請幫我。
我認為最簡單的方法是從文件中讀取所有整數並使用計數器填充2D數組:
public static int[][] readFile(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
int rows = scan.nextInt();
int cols = scan.nextInt();
int[][] res = new int[rows][cols];
for (int row = 0, col = 0; row < rows; ) {
res[row][col++] = scan.nextInt();
if (col == cols) {
row++;
col = 0;
}
}
return res;
}
}
您的“ 2D數組”代碼看起來不錯,您准備了“空”數組,然后根據其尺寸進行循環。
您問題的實質體現在這里:
java.util.Scanner.throwFor(Scanner.java:862)處的java.util.NoSuchElementException
重點是: 在讀取文件時,您最終會遇到錯誤。 無論您是僅將值打印到控制台,還是將它們存儲在該預定義的數組中,這都無關緊要。
換句話說:在這一點上,你的問題是,你的文件內容不符合您的期望/假設。 因此,您要求輸入一個數字……在沒有數字的地方。
答案:退后一步。 從一個很小的文件開始,該文件僅包含2 2 5 1 2 3 4
。 現在,使用該代碼運行您的代碼,然后打印所有相關信息(例如,從文件中讀取的值)。 使您了解您的代碼到底在做什么。
換句話說:需要調試。 通過實際使用調試器或添加打印語句。 您需要能夠觀察您的代碼完成其工作。
您得到的錯誤主要是因為您的文本文件不包含您的代碼試圖獲取的元素。
import java.io.File;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception {
// pass the path to the file as a parameter
File file =
new File("C:\\Users\\LENOVO\\Documents\\test.txt");
Scanner sc = new Scanner(file);
int rowLength = 0;
int colLength = 0;
int radius = 0;
rowLength = sc.nextInt();
colLength = sc.nextInt();
radius = sc.nextInt();
int[][] data = new int[rowLength][colLength];
System.out.println("ROW : " + rowLength + " COl : " + colLength + " Radius : " + radius);
for (int i = 0; i < rowLength; ++i) {
for (int j = 0; j < colLength; ++j) {
if (sc.hasNextInt()) {
data[i][j] = sc.nextInt();
}
}
}
// printing the array
for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < colLength; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.