我試圖讓掃描儀讀取文件並刪除每個單詞之間的空格。我可以得到這麼多,但我不能把它放在他們留在同一條線上的地方。我無法讓程序讀取一行,刪除空格,然後轉到下一行。這是從我的實踐項目中顯示:Java使用掃描儀讀取文件,然後讀取線
four score and seven years ago our fathers brought forth on this continent a new nation
我目前只獲得了第一線
,這是我的代碼:
import java.util.*;
import java.io.*;
public class CollapseSpace {
public static void main (String[] args) throws FileNotFoundException{
Scanner fileInput = new Scanner(new File ("textwithspaces.txt"));
String nextLine = fileInput.nextLine();
Scanner lineInput = new Scanner(nextLine);
while(fileInput.hasNext()){
nextLine = fileInput.nextLine();
while(lineInput.hasNext()){
System.out.print(lineInput.next() + " "); // I tried to add a fileInput.NextLine() to consume the line but it isn't working properly
}
System.out.println();
}
}
}
我知道,行「nextLine = fileInput.nextLine() ;」沒有被使用,但我不知道如何去使它循環到文本中的下一行......它在第一行運行,然後什麼也沒有 – user8686545