【发布时间】:2013-12-18 13:33:57
【问题描述】:
如何从文件中“删除”一个字符。还有,文件里的东西怎么打印出来?
编写一个程序来读取文本文件,也许是小说的文本。程序将相同的文本复制到输出文件,除了所有无用的单词,如“the”、“a”和“an”都被删除。 (决定要删除的其他词。删除的词列表称为停止列表。)通过使用 hasNext() 和 next() 逐个标记读取文本文件标记来执行此操作,但只写出不在停止列表。
提示用户输入和输出文件的名称。保留输入文件的行结构。为此,请使用 nextLine() 读取每一行,然后为该行创建一个新的 Scanner。 (查看 Scanner 的在线文档。)对于每一行的 Scanner,使用 hasNext() 和 next() 扫描其标记。
public static void main(String[] args) throws IOException {
String fileName;
Scanner user = new Scanner(System.in);
System.out.print("File name: ");
fileName = user.nextLine().trim();
File file = new File(fileName);
PrintStream printfile = new PrintStream(file);
System.out.println("Input data into file: ");
String datainfile = user.nextLine();
Scanner scan = new Scanner(file);
printfile.println(datainfile);
while (scan.hasNextLine()) {
while (scan.hasNext()) {
String character = scan.next();
if (character.equals("a")) {
}
}
}
}
编辑 感谢peeskillet,我再次尝试尝试。但是,我的程序中似乎有一个错误,我得到:
AAApotatopotatopotatojava.util.Scanner[delimiters=\p{javaWhitespace}+][position=0] [match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
你能检查我的程序吗?
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Input File name: ");
String filename1 = keyboard.nextLine().trim();
System.out.print("Output File name: ");
String filename2 = keyboard.nextLine().trim();
File inputFile = new File(filename1);
File outputFile = new File(filename2);
PrintStream printfile = new PrintStream(inputFile);
System.out.println("Input data into file: ");
String datainfile = keyboard.nextLine();
printfile.println(datainfile);
Scanner inFile = new Scanner(inputFile);
PrintWriter writeFile = new PrintWriter(outputFile);
Scanner lineScanner;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String word = lineScanner.next();
if(!(word.equals("a"))) {
writeFile.print(word + " ");
System.out.print(word);
}
if(!(word.equals("an"))) {
writeFile.print(word + " ");
System.out.print(word);
}
if(!(word.equals("the"))) {
writeFile.print(word + " ");
System.out.print(word);
}
else {
writeFile.print(" ");
}
}
writeFile.println();
}
writeFile.close();
Scanner readOutput = new Scanner(outputFile);
System.out.println(readOutput);
}
}
【问题讨论】:
-
您面临的具体问题是什么?
-
所有无用的词如“the”、“a”和“an”都被删除你的教授必须是俄语。
-
你检查过类似的问题吗?例如。 stackoverflow.com/questions/1664489/…