![](/img/trans.png)
[英]java: Read text file and store the info in an array using scanner class
[英]Java - How to store values of a text file into an array using Scanner?
import java.io.*;
import java.util.*;
import java.text.*;
public class textFile {
public static void main(String args[]) throws IOException {
Scanner sf = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
int maxIndx = -1;
String text[] = new String[1000];
while (sf.hasNext()) {
maxIndx++;
text[maxIndx] = sf.nextLine();
}
sf.close();
double average[] = new double[100];
for (int j = 0; j <= maxIndx; j++) {
Scanner sc = new Scanner(text[j]);
int k = 0;
while (k <= 10) { //attempt to store all the values of text file (DataGym.in.txt) into the array average[] using Scanner
average[k] = sc.nextDouble();
k++;
}
}
}
}
我的代碼不起作用,並在我將 sc.nextDouble() 存儲到數組的 k 元素的位置不斷給我這個錯誤:
java.util.NoSuchElementException:
null(在 java.util.Scanner 中)
您應該查看Scanner API 。 可疑的是,您調用Scanner.hasNext()
並隨后調用Scanner.nextLine()
。 有免費電話檢查,然后從Scanner
獲得。 舉例來說,如果你真的想下一行,那么你應該檢查是否Scanner.hasNextLine()
調用之前Scanner.nextLine()
類似地,您在調用Scanner.nextDouble()
之前沒有調用Scanner.hasNextDouble()
。
也像一些評論提到的那樣,您應該使用調試器或打印語句來查看您是否得到了您期望的結果。 像這樣的步驟是調試所必需的。
例如,在sf.close
之后,您可以使用System.out.println(Arrays.toString(text))
並判斷數組是否包含您期望的內容。
希望這有助於您的調試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.