[英]taking in input from a file in java
我不能為我的生活似乎接受這個文件的內容,我繼續得到第25行沒有這樣的元素異常,所有幫助欣賞。 下面是文件鏈接的鏈接
繼承我的代碼
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class practiceFinal {
public static void main(String[] args) {
String fileName = args[0];
int length = fileLength(fileName);
int[] array = new int[length];
String[] list = new String[length];
arrayPopulate(array, list, fileName);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
}
public static int fileLength(String fileName) {
File file = new File(fileName);
Scanner fileScan = new Scanner(fileName);
int counter = 0;
while (fileScan.hasNext()) {
fileScan.next();
counter++;
}
return counter;
}
public static void arrayPopulate(int[] array, String[] list, String fileName) {
File file = new File(fileName);
Scanner fileScan = null;
try {
fileScan = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("details: " + e.getMessage());
}
for (int i = 0; i < array.length; i++) {
array[i] = fileScan.nextInt();
list[i] = fileScan.next();
}
}
}
而不是使用int length = fileLength(fileName); 要查找長度,請使用int length = fileName.length();
從文件格式和當前代碼看, length
表示文件中“單詞”的數量。 在你的循環中,你需要將i
提前2而不是1,因為它每次迭代消耗兩個“單詞”。 這也意味着每個陣列的長度應該是它應該的兩倍。 使用length/2
實例化它們。
for (int i = 0; i < array.length; i += 2) {
array[i] = fileScan.nextInt();
list[i] = fileScan.next();
}
或者,您可以使length
表示文件中的行數。 為此,請在計數循環中使用hasNextLine()
和nextLine()
。 然后保留所有其余代碼。
while (fileScan.hasNextLine()) {
fileScan.nextLine();
counter++;
}
此外,請確保您的Scanner
通過了適當的參數。 String
有效,但不適用於文件I / O. 您需要首先使用fileName
創建File
對象。
Scanner fileScan = new Scanner(new File(fileName));
這里有一些問題。 首先,您使用的是fileScan.next();
嘗試獲取文件的長度。 這將給你2倍的長度,因為你在計算每個令牌fileScan.next()
抓取哪個先是數字然后是字母。
線條長度為144,但是當你計算它時,它返回288。
所以使用fileScan.nextLine();
,現在有些人已經提到過這個,但是你的程序仍然無法正常工作,因為你傳遞了Scanner fileScan = new Scanner(fileName); // mistake passed fileName instead of file
Scanner fileScan = new Scanner(fileName); // mistake passed fileName instead of file
以下是我在fileLength()方法中所做的更改:
File file = new File(fileName);
Scanner fileScan = new Scanner(file); // mistake passed fileName instead of file, changed from Scanner fileScan = new Scanner(fileName)
while (fileScan.hasNextLine()) {
fileScan.nextLine(); // changed from fileScan.next()
counter++;
}
您的輸出如下:
84c89C11w71h110B96d61H92d10B3p40c97G117X13....
在打印結果時,請將打印語句更改為
System.out.print(array[i]);
System.out.print(" " + list[i]);
System.out.println();
輸出現在看起來像:
84 c
89 C
11 w
71 h
....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.