[英]How to read the last group of numbers on a line in a .txt file in Java
我目前有一個文本文件,如下所示:
Bob Peach 1000 115
Hugh Mungus 1001 250
Joe Bloggs 1003 555
Joe Walsh 1004 6
Ben Davis 1005 1
我需要閱讀該行的最后一組數字,將它們加在一起,然后將答案輸出到單獨的文本文件中。 我將如何處理?
編輯:預期結果應該是在輸出文件中的一個字符串,如下所示:
There are currently 927 points.
編輯2:抱歉,我們沒有更好地解釋它,但我現在修改了使用實際名稱而不是僅使用占位符的虛擬文件的外觀。 如您所見,最后一組數字之前的字符數並不總是相同。
編輯3:這是我在等待回復時嘗試過的方法,通常我認為它應該起作用。
public void processFiles()
{
total = 0;
while(input.hasNextInt())
{
input.nextInt();
total = total + input.nextInt();
input.nextLine();
}
output.print("There are all together " +
total + " points.");
}
但是上面的代碼只是輸出有0點。
編輯4:
public void processFiles()
{
total = 0;
while(input.hasNext())
{
String line = input.nextLine();
String[] splitLine = line.split(" ");
total += Integer.parseInt(splitLine[splitLine.length - 1]);
}
output.print("There are all together " +
total + " points.");
}
假設僅提供了信息(行項目由單個空格分隔,最后一項始終是您想要的數字),則可以讀取文件中的每一行並在每一行中執行以下操作。
String[] splitLine = line.split(" ");
total += Integer.parseInt(splitLine[splitLine.length - 1]);
閱讀文件並遍歷每一行作為練習留給讀者。
嘗試這樣的事情...
您只需逐行讀取文件,使用space
字符將每一行拆分,然后將行的最后一部分轉換為integer
。
int sum=0;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] res = line.split(" ");
sum = sum + Integer.parseInt(res[res.length - 1]);
}
}
如果字符串始終具有相同的行數,則可以使用這種方法
String LikesDislikes = "Likes: 10
Dislikes:10"
String[] lines = LikesDislikes.split("\\n");
String likes = lines[0];
String dislikes = lines[1];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.