【发布时间】:2015-03-28 23:34:05
【问题描述】:
我有一个程序,用于分析用户通过在提示时输入文本文件的完整路径来选择的文本文件。
我已设法将扫描仪分为多个类,但它不会同时适用于每种方法。例如,我有一个类将打印文件中的数字数量,另一个类将打印文件中的字数。然而,只有第一个运行的方法会起作用,另一个将显示类正在搜索的任何内容(数字、行、单词等)的 0,即使真实值实际上不是 0。
我真的很困惑为什么会发生这种情况,我已将主类与其他两个类附加在一起以显示一个清晰的示例:
主类:
package cw;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class TextAnalyser {
public static Scanner reader;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter a filename");
String filename = in.nextLine();
File InputFile = new File (filename);
reader = new Scanner (InputFile);
LineCounter Lineobject = new LineCounter();
WordCounter Wordobject = new WordCounter();
Lineobject.TotalLines();
Wordobject.TotalWords();
}
}
计算行数的类:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class LineCounter {
public static void TotalLines() throws IOException {
// Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
Scanner sc = TextAnalyser.reader;
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt", true));
int linetotal = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linetotal++;
}
out.println("The total number of lines in the file = " + linetotal);
out.flush();
out.close();
System.out.println("The total number of lines in the file = " + linetotal);
}
}
单词计数类:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class WordCounter {
public static Scanner sc = TextAnalyser.reader;
public static void TotalWords() throws IOException{
//Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt", true));
int wordtotal = 0;
while (sc.hasNext()){
sc.next();
wordtotal++;
}
out.println("The total number of words in the file = " + wordtotal);
out.flush();
out.close();
System.out.println("The total number of words in the file = " + wordtotal);
}
}
由于某种原因,一次只能工作一个,总是说有 0 个,如果有人可以向我解释为什么会发生这种情况以及如何解决它,那真的很有帮助,谢谢!
【问题讨论】:
-
你在哪里使用
Scanner reader?TextAnalyser是什么? -
TextAnalyser 是主类的名称,reader 在里面声明。
-
哦,对不起,我很困惑..让我再看看。
标签: java class java.util.scanner