![](/img/trans.png)
[英]Read text file for integers and storing to array using scanner and exceptions
[英]Using scanner to read integers from a file into an array
我正在為學校做一份復習工作。 賦值是編寫一個類,它從標准輸入讀取一個包含幾個整數的文件,這些整數將被放入一個數組中。 從這里開始,需要編寫方法來找出平均值,中位數,最大值,最小值和標准差。
它讀起來像這樣:
45
56
67
78
89等...
所以,我假設我需要創建一個數組列表(因為長度未定義)並使用scanner讀取每一行的整數,然后創建將挑選我需要的方法。 但是,我無法理解如何正確使用FileReader和Scanner。 我目前正在運行BlueJ。 文本文件位於項目文件夾下,但代碼永遠找不到該文件。
這是我到目前為止所擁有的。
import java.io.*;
import java.util.*;
import java.math.*;
public class DescriptiveStats
{
public DescriptiveStats(){}
public FileReader file = new FileReader("students.txt");
public static void main(String[] args) throws IOException
{
try{
List<Integer> scores = new ArrayList<Integer>();
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
scores.add(sc.nextInt());
}
sc.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
確保“students.txt”與您運行的代碼位於同一目錄中(例如,將.java文件編譯到的目錄),或者將完整路徑放到文件中。(“C:/ folder / students” 。文本”)
System.out.println(new File("students.txt").getAbsolutePath());
將為您提供java嘗試加載文件的路徑。
我懷疑它是由於類路徑中的多個路徑引起的歧義,第一個條目是它加載的那個。 將文件加載路徑設置為第一個條目應該可以解決問題。
使用Scanner.hasNextInt() (而不是Scanner.hasNext() ):
...
while(sc.hasNextInt())
{
scores.add(sc.nextInt());
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.