我目前正在尝试比较文本文件中的行以找到最短行和最长行并显示每行中有多少个字符。下面列出的代码允许我计算所有字符、单词和行数。我不知道从哪里开始比较线条?任何帮助将不胜感激。
import java.util.Scanner;
import java.io.*;
public class Test{
public static void main(String [] args){
System.out.println("Please enter the filename: ");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
FileReader fReader;
try {
fReader = new FileReader(fileName);
BufferedReader reader = new BufferedReader(fReader);
String cursor; //
String content = "";
int lines = 0;
int words = 0;
int chars = 0;
while((cursor = reader.readLine()) != null){
// count lines
lines += 1;
content += cursor;
// count words
String []_words = cursor.split(" ");
for( String w : _words)
{
words++;
}
}
chars = content.length();
System.out.println("The filename is " + fileName);
System.out.println(chars + " Characters,");
System.out.println(words + " words and " + lines + " lines.");
} catch (FileNotFoundException ex) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("File not found!");
} catch (IOException ex) {
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("An error has occured: " + ex.getMessage());
}
}
}
最佳答案
您必须创建 2 个变量来存储短行和长行...
String longest = "";
String shortest = "";
然后在现有代码中,与当前行进行比较:
while((cursor = reader.readLine()) != null){
// compare shortest and longest.
int currentSize = cursor.lenght;
if (currentSize > longest.lenght || longest.equals("")) {
longest = cursor;
} else if (currentSize < shortest.lenght || longest.equals("")) {
shortest = cursor;
}
// count lines
lines += 1;
content += cursor;
// count words
String []_words = cursor.split(" ");
for( String w : _words)
{
words++;
}
}
循环结束后,您可以对结果执行所需的操作:
System.out.println("Longest line has " + longest.lenght);
System.out.println("Shortest line has " + shortest.lenght);
如果您只需要尺寸而不需要线条,您可以创建 int
变量。
int longest = 0;
int shortest = 0;
// then inside the loop
int currentSize = cursor.lenght;
if (currentSize > longest || currentSize = 0) {
longest = currentSize;
} else if (currentSize < shortest || currentSize = 0) {
shortest = currentSize;
}
关于java - 尝试比较文本文件中的代码行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29235336/