我想讀取文本文件的線條,走數字的平均值。我的計劃是先讀取文本文件中的所有數據。然後將字符串分成一個字符串數組,然後將每個索引解析爲一個int
數組。這是我的代碼,直到閱讀文檔。如何在一個文本文件中讀取值,然後進行再分析它們以整數的JAVA
我的文本文檔:
3,7,24,66,
10,50,20,40,
100,20,69,911,
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Testing
{
public static void main(String[] args) throws IOException
{
try
{
String path;
path = "TestNumbers.txt";
File f = new File(path);
FileReader re = new FileReader(f);
BufferedReader in = new BufferedReader(re);
String line = "";
String store = "";
while((line = in.readLine()) != null)
{
store = store + line;
}
System.out.println(store);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
輸出:3,7,24,66,10,50,20,40,100,20,69,911,
在一個完美的世界中,我希望值被eit她「,」或「」。
我試着修改store = store + line + " ";
,但是這樣做失敗了,因爲即使readLine()
在空行上,它也會迭代空間。
我可以遍歷數組來解析int
並取平均值,但是設置這個字符串被分割會困擾我。我試過String.replace()
,String.trim()
,和另外一個失敗的我。這不是家庭作業,我在高中AP CS,這是我自己的獨立研究。
感謝大家的幫助,你都表現出很多方法可以做到這一點。結束後,使用.replace,並將「」變成「」。然後通過逗號分開。儘管如此,我還是想嘗試一下這個正則表達式。再次感謝大家。
調查Sting.split()。它有你在找什麼。 – user3473949 2014-10-17 02:44:07
@ user3473949 OP已經提過關於 – DnR 2014-10-17 02:44:43
'if(line.length()> 0){store = store + line;}' – 2014-10-17 02:47:02