Java 排序字符

Java 排序字符,java,arrays,Java,Arrays,我试图编写一个代码,计算文件中的行数和字符数,然后对任何字符(包括空格和逗号)进行排序 我想到了什么 import java.io.BufferedReader; File file1 = new File("C:/input.txt"); BufferedReader in = new BufferedReader(new FileReader(file1)); int nextChar; char ch;

我试图编写一个代码,计算文件中的行数和字符数,然后对任何字符(包括空格和逗号)进行排序

我想到了什么

import java.io.BufferedReader;


        File file1 = new File("C:/input.txt");
        BufferedReader in = new BufferedReader(new FileReader(file1));

        int nextChar;
        char ch;

        int[] count = new int[1000];





        in.close();
    }
}

提前谢谢

好的,这里的棘手问题是如何按降序对原始类型
int
的数组进行排序?这个网站上有很多帖子都在谈论
array.sort(array,Collections.reverseOrder())
但这只能用于对象数组,而不能用于
int
等基本类型。因此,最好的方法是使用内置的
Arrays
方法按升序对数组进行排序,然后遍历整个数组以反转数组中的元素。因此,您应该考虑在程序结束时添加代码片段,

Arrays.sort(count);//sort in ascending order
for(int i = 0; i < count.length; i++){ //reversing the order of the array
    int k = count[i]; //swapping the i-th element with the i-th to last element
    count[i] = count[count.length - 1 - i];
    count[count.length - 1 - i] = k;
}
Arrays.sort(count)//按升序排序
对于(int i=0;i
就我个人而言,我建议将上面的代码放在for循环之前

for (i = 0; i < 26; i++) {

    System.out.printf("%c : %d", i + 'A', count[i]);

    System.out.println("");
}
(i=0;i<26;i++)的
{
System.out.printf(“%c:%d”,i+'A',count[i]);
System.out.println(“”);
}

好的,这里的棘手问题是如何按降序对基本类型
int
的数组进行排序?这个网站上有很多帖子都在谈论
array.sort(array,Collections.reverseOrder())
但这只能用于对象数组,而不能用于
int
等基本类型。因此,最好的方法是使用内置的
Arrays
方法按升序对数组进行排序,然后遍历整个数组以反转数组中的元素。因此,您应该考虑在程序结束时添加代码片段,

Arrays.sort(count);//sort in ascending order
for(int i = 0; i < count.length; i++){ //reversing the order of the array
    int k = count[i]; //swapping the i-th element with the i-th to last element
    count[i] = count[count.length - 1 - i];
    count[count.length - 1 - i] = k;
}
Arrays.sort(count)//按升序排序
对于(int i=0;i
就我个人而言,我建议将上面的代码放在for循环之前

for (i = 0; i < 26; i++) {

    System.out.printf("%c : %d", i + 'A', count[i]);

    System.out.println("");
}
(i=0;i<26;i++)的
{
System.out.printf(“%c:%d”,i+'A',count[i]);
System.out.println(“”);
}

您可以使用一个映射,然后使用自编比较器对其进行排序(我从线程中窃取了代码),这样您就不必预先定义要计数的字符(就像使用数组一样)

这看起来像这样:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class CountCharsFromFile {
    static BufferedReader b;

    public static void main(String[] args) {

        try {
            FileReader fr = new FileReader("C:\\test.txt");
            b = new BufferedReader(fr);

            Map<String, Double> count = new HashMap<String,Double>();
            ValueComparator bvc = new ValueComparator(count);
            TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);

            int totalChars = 0;
            int totalWords = 0;

            String currentLine;

            while ((currentLine = b.readLine()) != null){
                for (int i = 0; i < currentLine.length(); i++) {

                    //Char count:
                    totalChars += 1;

                    //Adding all chars to the Map:
                    char currentChar = Character.toLowerCase(currentLine.charAt(i));

                    if (! count.containsKey(String.valueOf(currentChar))){
                        count.put(String.valueOf(currentChar), 1.0);
                    }else{
                        count.put(String.valueOf(currentChar), count.get(String.valueOf(currentChar)) + 1);
                    }

                }

                //Counting words:

                String[] currentLineSplit= currentLine.split("\\s+");

                for (String string : currentLineSplit) {
                    totalWords += 1;
                }

            }

            sorted_map.putAll(count);

            //Output:
            System.out.println("Words: " + totalWords);
            System.out.println("Chars: " + totalChars);
            System.out.println(sorted_map.toString());


        } catch (FileNotFoundException e) {
            System.err.println("Error, file not found!");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Error reading file!");
            e.printStackTrace();
        }finally{
            try {
                b.close();
            } catch (IOException e) {
                System.err.println("Couldn't close the BufferedReader!");
                e.printStackTrace();
            }

        }

    }
}




//comparator class:

class ValueComparator implements Comparator<String> {
    Map<String, Double> base;

    public ValueComparator(Map<String, Double> base) {
        this.base = base;
    }

    // Note: this comparator imposes orderings that are inconsistent with
    // equals.
    public int compare(String a, String b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }
}
Words: 9
Chars: 59
{ =16.0, h=7.0, i=5.0, r=4.0, c=4.0, �=3.0, s=3.0, o=3.0, l=3.0, f=3.0, ,=2.0, w=1.0, u=1.0, n=1.0, m=1.0, b=1.0, a=1.0}
Words: 9
Chars: 60

SPACE = 8
R = 6
T = 5
E = 5
A = 5
N = 3
U = 2
O = 2
M = 2
L = 2
I = 2
H = 2
. = 1
Z = 1
Y = 1
X = 1
W = 1
V = 1
S = 1
Q = 1
P = 1
K = 1
J = 1
G = 1
F = 1
D = 1
C = 1
B = 1
“sorted_map.toString()”的输出不是很好,因此我编写了一个快速输出方法:

static void output(TreeMap<String, Double> sm) {

        String map = sm.toString();

        if (map.length() > 2) { //If the map is empty it looks like this: {}

            map = map.substring(1, map.length() - 1); //cutting the leading and closing { }

            String[] charCount = map.split(", "); //Splitting

            //And then formatting:
            for (String string : charCount) {
                if (string.charAt(0) == ' ') {

                    string = string.substring(1, string.length() - 2);
                    string = " " + string.substring(0, 1) + " " + string.substring(1, string.length());
                    System.out.println("SPACE" + string);

                } else {

                    string = string.substring(0, string.length() - 2);
                    string = string.substring(0, 1) + " " + string.substring(1, 2) + " "
                            + string.substring(2, string.length());
                    System.out.println(string);
                }
            }

        }

    }

现在,它变得有点混乱(比较器破坏了“TreeMap.get”方法,所以我不得不使用子字符串构建一个变通方法),但我希望这会对您有所帮助:)

您可以使用一个映射,然后使用一个自写的比较器进行排序(我从线程中窃取了代码),这样,您就不必预先定义要计数的字符(就像使用数组一样)

这看起来像这样:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class CountCharsFromFile {
    static BufferedReader b;

    public static void main(String[] args) {

        try {
            FileReader fr = new FileReader("C:\\test.txt");
            b = new BufferedReader(fr);

            Map<String, Double> count = new HashMap<String,Double>();
            ValueComparator bvc = new ValueComparator(count);
            TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);

            int totalChars = 0;
            int totalWords = 0;

            String currentLine;

            while ((currentLine = b.readLine()) != null){
                for (int i = 0; i < currentLine.length(); i++) {

                    //Char count:
                    totalChars += 1;

                    //Adding all chars to the Map:
                    char currentChar = Character.toLowerCase(currentLine.charAt(i));

                    if (! count.containsKey(String.valueOf(currentChar))){
                        count.put(String.valueOf(currentChar), 1.0);
                    }else{
                        count.put(String.valueOf(currentChar), count.get(String.valueOf(currentChar)) + 1);
                    }

                }

                //Counting words:

                String[] currentLineSplit= currentLine.split("\\s+");

                for (String string : currentLineSplit) {
                    totalWords += 1;
                }

            }

            sorted_map.putAll(count);

            //Output:
            System.out.println("Words: " + totalWords);
            System.out.println("Chars: " + totalChars);
            System.out.println(sorted_map.toString());


        } catch (FileNotFoundException e) {
            System.err.println("Error, file not found!");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Error reading file!");
            e.printStackTrace();
        }finally{
            try {
                b.close();
            } catch (IOException e) {
                System.err.println("Couldn't close the BufferedReader!");
                e.printStackTrace();
            }

        }

    }
}




//comparator class:

class ValueComparator implements Comparator<String> {
    Map<String, Double> base;

    public ValueComparator(Map<String, Double> base) {
        this.base = base;
    }

    // Note: this comparator imposes orderings that are inconsistent with
    // equals.
    public int compare(String a, String b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }
}
Words: 9
Chars: 59
{ =16.0, h=7.0, i=5.0, r=4.0, c=4.0, �=3.0, s=3.0, o=3.0, l=3.0, f=3.0, ,=2.0, w=1.0, u=1.0, n=1.0, m=1.0, b=1.0, a=1.0}
Words: 9
Chars: 60

SPACE = 8
R = 6
T = 5
E = 5
A = 5
N = 3
U = 2
O = 2
M = 2
L = 2
I = 2
H = 2
. = 1
Z = 1
Y = 1
X = 1
W = 1
V = 1
S = 1
Q = 1
P = 1
K = 1
J = 1
G = 1
F = 1
D = 1
C = 1
B = 1
“sorted_map.toString()”的输出不是很好,因此我编写了一个快速输出方法:

static void output(TreeMap<String, Double> sm) {

        String map = sm.toString();

        if (map.length() > 2) { //If the map is empty it looks like this: {}

            map = map.substring(1, map.length() - 1); //cutting the leading and closing { }

            String[] charCount = map.split(", "); //Splitting

            //And then formatting:
            for (String string : charCount) {
                if (string.charAt(0) == ' ') {

                    string = string.substring(1, string.length() - 2);
                    string = " " + string.substring(0, 1) + " " + string.substring(1, string.length());
                    System.out.println("SPACE" + string);

                } else {

                    string = string.substring(0, string.length() - 2);
                    string = string.substring(0, 1) + " " + string.substring(1, 2) + " "
                            + string.substring(2, string.length());
                    System.out.println(string);
                }
            }

        }

    }

现在,它变得有点混乱(comparator破坏了“TreeMap.get”方法,因此我不得不使用子字符串构建一个解决方案),但我希望这会对您有所帮助:)

编辑问题以包含程序的当前输出,以便我们能够更好地理解问题。如果您不能这样做,请解释编译器错误发生的位置编辑问题以包括程序的当前输出,这样我们可以帮助更好地理解问题。如果您不能做到这一点,请解释编译器错误在这一行ValueComparator bvc=new ValueComparator(count)上发生的位置。有个错误。它说非静态变量这不能从静态上下文引用好吧,我刚刚修复了代码中的两个小错误,但我真的不知道为什么它会告诉你某些东西不是静态的。。。如果在main()方法中声明它,它应该始终是静态的。我只是复制粘贴的代码再次和它的作品为我好哦愚蠢的我。现在很好用。除了通话部分。我可以运行这个程序。它显示了结果,但有一些错误。你能帮我一个忙吗?取决于你的帮助,如果不是关于这个话题,也许我们应该把这个对话转到电子邮件:fingereric@web.deon此行ValueComparator bvc=新的ValueComparator(计数)。有个错误。它说非静态变量这不能从静态上下文引用好吧,我刚刚修复了代码中的两个小错误,但我真的不知道为什么它会告诉你某些东西不是静态的。。。如果在main()方法中声明它,它应该始终是静态的。我只是复制粘贴的代码再次和它的作品为我好哦愚蠢的我。现在很好用。除了通话部分。我可以运行这个程序。它显示了结果,但有一些错误。你能帮我一个忙吗?取决于你的帮助,如果不是关于这个话题,也许我们应该把这个对话转到电子邮件:fingereric@web.de