如何编辑我的代码以计算并显示每个名称在我的列表中出现的次数

时间:2015-11-09 00:15:21

标签: java arrays string arraylist counter

由于这是初学者课程,我们没有谈到我在这里阅读的许多解决方案,所以我想根据我的代码询问我该怎么办。

对于文件中的每个名称,(姓氏后跟逗号,后跟一个或多个空格,后跟名字)显示名称在文件中出现的次数。 (即姓名:伯爵)。此名称列表必须按名称的升序显示。所有名字和姓氏必须大写。每个名称只能显示一次。

       ******* First Names count*********
       Adriana 4
       Colette 4
       Emmanuel 1
       Gerri 1
       Gretta 1
       Kirsten 2
       Marcia 2
       Neva 1
       Shawanda 1

这就是我到目前为止......

public static void main(String[] args) throws IOException {
    // TODO code application logic here
    ArrayList<String> first = new ArrayList<>();
    ArrayList<String> last = new ArrayList<>();
    getNames(first, last);
    //display(first);
    //display(last);
    capitalize(first, last);
    //capitalize(last);
    ArrayList<String> allNames = new ArrayList<>();
    for (int i = 0; i < first.size(); i++) {
        allNames.add(last.get(i) + ", " + first.get(i));
    }
    ArrayList<String> capNames = new ArrayList<>();

    System.out.println("***************All Names************");
    //System.out.println(allNames);
    //capitalize(allNames);
    display(allNames);

}

/**
* @param fn
* @param ln
*
* @throws java.io.IOException
*/

public static void getNames(ArrayList<String> fn,
                            ArrayList<String> ln) throws IOException {

    Scanner kb = new Scanner(System.in);

    System.out.print("What is the name input file? ");

    String fileName = kb.next();

    File inpFile = new File(fileName);
    Scanner in = new Scanner(inpFile);

    while (in.hasNext()) {
        String firstName = in.next();
        String lastName = in.next();
        fn.add(firstName);
        ln.add(lastName);
    }

}

public static void capitalize(ArrayList<String> first,
                                ArrayList<String> last) {

    for (int i=0; i<first.size(); i++) {
        String capFirst = first.get(i).substring(0,1).toUpperCase() 
                        + first.get(i).substring(1).toLowerCase();
        first.set(i, capFirst);
    }

    for (int i=0; i<last.size(); i++) {
        String capLast = last.get(i).substring(0, 1).toUpperCase() +
                        last.get(i).substring(1).toLowerCase();
        last.set(i, capLast);
    }
}     

public static void display(ArrayList<String> allNames) {

    for (int i = 0; i < allNames.size(); i++) {
        System.out.println(allNames.get(i));
    }

} 

2 个答案:

答案 0 :(得分:1)

在代码中查看我的评论。我会修改你的代码做这样的事情:)

在您的代码中,读取文件的方法不正确,因为名字和姓氏在用逗号分隔的同一行上。因此,我们需要读取此行并将名字和姓氏分成单独的字符串。但是你后来的评论声明没有逗号,在这种情况下你需要修改getNames()方法来满足这个要求。

我使用HashMap存储名字及其出现次数。

import java.util.ArrayList;
import java.io.*;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test {

    private ArrayList<String[]> allNames;

    public static void main(String[] args) throws IOException {

        Test t = new Test();
        t.go();
    }

    public void go() {

        try {
            this.getNames();
            this.printAll();
            this.printFirstNamesCount();
        }
        catch(IOException ioEx) {

            System.out.println("Input file error. Info : " + ioEx.getMessage());
        }
    }

    private void getNames() throws IOException {

        allNames = new ArrayList<String[]>();
        Scanner kb = new Scanner(System.in);
        System.out.print("What is the name input file? ");
        String fileName = kb.next();
        File inpFile = new File(fileName);
        Scanner in = new Scanner(inpFile);

        while (in.hasNext()) {

            //slot the string into a arry (last name, first name)
            //use nextLine() or it won't read beyond spaces
            String[] tmp = in.nextLine().split(",");
            //remove white spaces in the first name
            tmp[1] = tmp[1].replaceAll("\\s+","");
            //capitalize both first and last names
            tmp[0] = capitalize(tmp[0]);
            tmp[1] = capitalize(tmp[1]);
            allNames.add(tmp);
        }
    }

    private void printAll() {

        System.out.println("******* All Names *********");

        for(String[] tmp : allNames) {

            //array index 1 is they first name and 0 is the last name
            System.out.println(tmp[1] + " " + tmp[0]);
        }
    }

    private void printFirstNamesCount() {

        HashMap<String, Integer> firstNamesCount = new HashMap<String, Integer>();

        for(String[] tmp : allNames) {

            //we haven't counted this first name yet
            if(firstNamesCount.get(tmp[1]) == null) {

                firstNamesCount.put(tmp[1], 1);
            }
            //we have counted this name, so let's just increment it
            else {

                firstNamesCount.put(tmp[1], (firstNamesCount.get(tmp[1]) + 1));
            }
        }

        //now let's print the hash map

        System.out.println("******* First Names Count *********");

        for(Map.Entry<String, Integer> e : firstNamesCount.entrySet()) {

            System.out.println(e.getKey() + " - " + e.getValue());
        }
    }

    //capitalize the first letter
    private String capitalize(String line) {

        return Character.toUpperCase(line.charAt(0)) + line.substring(1);
    }
}

我的输入文件看起来像这样,

Gunasekara, Achintha
Gun,  Achintha
Simpson, Homer
Simpson, Bart
Singclar, James
Silver, Paul
Sil, Paul,
Si,   Paul,
Kang, David

你应该得到一个看起来像

的输出
Archies-MacBook-Pro:Downloads archieg$ java Test 
What is the name input file? test.txt
******* All Names *********
Achintha Gunasekara
Achintha Gun
Homer Simpson
Bart Simpson
James Singclar
Paul Silver
Paul Sil
Paul Si
David Kang
******* First Names Count *********
James - 1
David - 1
Homer - 1
Achintha - 2
Paul - 3
Bart - 1
Archies-MacBook-Pro:Downloads archieg$

答案 1 :(得分:1)

我稍微修改了你的代码 我添加了静态类NameInf来携带名称“名字及其计数到目前为止”的信息

并添加方法firstNameCounts,搜索第一个arraylist以查找重复名称的计数^ - ^

static class NameInf {

    String name;
    int count = 0;

    public NameInf(String name) {
        this.name = name;
    }

    @Override
    //overide default equal method so two object are equal if with same
    //name even they are not have same refence
    public boolean equals(Object obj) {
        if (obj instanceof NameInf) {
            NameInf casted = (NameInf) obj;
            return casted.name.equals(this.name);
        } else {
            return false;
        }
    }

}

public static void main(String[] args) throws IOException {
    // TODO code application logic here
    ArrayList<String> first = new ArrayList<>();
    ArrayList<String> last = new ArrayList<>();
    getNames(first, last);
    //display(first);
    //display(last);
    capitalize(first, last);
    //capitalize(last);
    ArrayList<String> allNames = new ArrayList<>();
    for (int i = 0; i < first.size(); i++) {
        allNames.add(last.get(i) + ", " + first.get(i));
    }
    //ArrayList<String> capNames = new ArrayList<>(); // used for what? 

    System.out.println("***************All Names************");
    //System.out.println(allNames);
    //capitalize(allNames);
    display(allNames);

    ArrayList<NameInf> fnc= firstNamesCount(first);
    for(NameInf ni : fnc){
        System.out.println(ni.name + " " + ni.count);
    }
}

/**
 * @param fn
 * @param ln
 *
 * @throws java.io.IOException
 */
public static void getNames(ArrayList<String> fn,
        ArrayList<String> ln) throws IOException {

    Scanner kb = new Scanner(System.in);

    System.out.print("What is the name input file? ");

    String fileName = kb.next();

    File inpFile = new File(fileName);
    Scanner in = new Scanner(inpFile);

    while (in.hasNext()) {
        String firstName = in.next();
        String lastName = in.next();
        fn.add(firstName);
        ln.add(lastName);
    }

}

public static void capitalize(ArrayList<String> first,
        ArrayList<String> last) {

    for (int i = 0; i < first.size(); i++) {
        String capFirst = first.get(i).substring(0, 1)
                .toUpperCase() + first.get(i).substring(1).toLowerCase();
        first.set(i, capFirst);
    }
    for (int i = 0; i < last.size(); i++) {
        String capLast = last.get(i).substring(0, 1).toUpperCase()
                + last.get(i).substring(1).toLowerCase();
        last.set(i, capLast);
    }
}

public static void display(ArrayList<String> allNames) {

    for (int i = 0; i < allNames.size(); i++) {

        System.out.println(allNames.get(i));

    }
}

public static ArrayList<NameInf> firstNamesCount(ArrayList<String> firstNames) {
    ArrayList<NameInf> temp = new ArrayList<>();
    for (String n : firstNames) {
        NameInf nameinf = new NameInf(n);
        int index = temp.indexOf(nameinf) ;
        if (index == -1) {
            nameinf.count = 1 ;
            temp.add(nameinf);
        }else{
            temp.get(index).count++;
        }
    }
    return temp ;
}