Java使用扫描仪读取文件,然后读取线
问题描述:
我试图让扫描仪读取文件并删除每个单词之间的空格。我可以得到这么多,但我不能把它放在他们留在同一条线上的地方。我无法让程序读取一行,删除空格,然后转到下一行。这是从我的实践项目中显示: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();
在循环之外,然后在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();
}
}
}
答
首先,您不应该使用*
来导入类。它通常被认为是“不好的做法”,因为它可能会干扰你自己的班级,也不是很明确。
您需要在您自己的循环内循环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循环,这是所以你可以立即进入循环,而无需首先检查条件,它在下一次迭代之前完成。
答
如果你只需要一行迭代行,然后删除单词之间有空格,那么你只需要一个循环,下面的示例代码应该做的伎俩
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 = fileInput.nextLine() ;”没有被使用,但我不知道如何去使它循环到文本中的下一行......它在第一行运行,然后什么也没有 – user8686545