试图比较文本文件中的代码行

时间:2015-03-24 14:33:54

标签: java

我目前正在尝试比较文本文件中的行以找到最短行和最长行,并显示每行中有多少个字符。我在下面列出的代码允许我计算所有字符,单词和行。我不知道从哪里开始比较线?任何帮助将不胜感激。

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 个答案:

答案 0 :(得分:1)

您必须创建2个vars来存储短行和长行......

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;
}

答案 1 :(得分:0)

您需要2个String变量,一个用于保存最短的String,另一个用于保存最长的String。然后在处理每一行时,将当前行的长度与最短/最长的行进行比较。

如果它短于最短的String,请将最短的String设置为当前行。

否则

如果它比最长的String长,请将最长的String设置为当前行。

最后在这两个String变量上处理结果。