java - 尝试比较文本文件中的代码行

标签 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 个变量来存储短行和长行...

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/

相关文章:

java - 如何从静态主方法依赖注入(inject)运行时参数

java - JAI 供应商名称 == null

java - 有没有办法配置jboss在线程执行结束时清除ThreadLocal变量?

java - AJAX JSON 数据检索(Portlet+Liferay+JSON+Spring)

java - 如何在Java中创建可分配的、类似数字的类?

数组中的 Java OutofBoundException

java - Android Studio - 单击图像按钮后崩溃

java - Mockito 模拟一个具有不相关静态方法的类

java - XPATH使用条件过滤不同内部路径中的元素

java - Young , Tenured 和 Perm 一代