[英]Java Using Scanner to Read File and Then Read Line
我正在尝试使扫描仪读取文件并删除每个单词之间的空格。 我可以得到很多,但是我不能到达他们停留在同一条线上的地方。 我无法让程序读取一行,删除空格,然后转到下一行。 这是我的实践项目的文本:
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();
}
}
}
如果只需要逐行迭代并删除单词之间的空格,则只需要一个循环,下面的示例代码应该可以解决问题
public static void main (String[] args) throws FileNotFoundException{
final Scanner fileInput = new Scanner(new File ("src/main/resources/textwithspaces.txt"));
while(fileInput.hasNext()){
final String nextLine = fileInput.nextLine();
// remove all spaces
final String lineWithOutSpaces = nextLine.replaceAll("\\s+","");
System.out.println(lineWithOutSpaces);
}
}
首先,您不应该使用*
导入类。 由于它会干扰您自己的班级,因此通常被认为是“不好的做法”,也不是很明确。
您需要在自己的循环中循环nextLine方法。 并且还可以使用字符串的replaceAll方法。
我在下面显示了一个示例:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class Main {
public static void main(String[] args) throws FileNotFoundException {
// Create an object to represent a text file
File file = new File("textwithspaces.txt");
// Create a scanner with the text file as argument
Scanner scannerWithFile = new Scanner(file);
// Continue as long as it has a next line
do {
// Replace strings
String thisLine = scannerWithFile.nextLine();
// Only print the line out if not empty
if (!thisLine.isEmpty()) {
// Replace all spaces
thisLine = thisLine.replaceAll(" ", "");
// Print
System.out.println(thisLine);
}
} while (scannerWithFile.hasNext());
}
}
我还将您的while循环切换为do while循环,这样您就可以立即进入循环,而不必先检查条件,它是在下一次迭代之前完成的。
最大的问题是您声明了nextLine = fileInput.nextLine();
在循环之外,然后在Scanner lineInput = new Scanner(nextLine);
使用它Scanner lineInput = new Scanner(nextLine);
因此它成为了文本的第一行,但从未改变。
我也同意另一条评论,即您不应该使用*
,这样广泛地导入被认为是不好的做法,因为您要导入很多您不会使用的东西。
我重构了您的代码以使其正常工作。
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main (String[] args) throws FileNotFoundException{
Scanner fileInput = new Scanner(new File ("textwithspaces.txt"));
while(fileInput.hasNext()){
String nextLine = fileInput.nextLine();
Scanner lineInput = new Scanner(nextLine);
while(lineInput.hasNext()){
System.out.print(lineInput.next() + " ");
}
System.out.println();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.