计算队列中以相同字母开头的国家名称总数

Calculate the total number of country names in the queue that begins with the same letter

我对如何计算队列中首字母相同的姓名的数量感兴趣。

我的程序会要求用户输入几个名字,这些名字会存储在一个队列中。但是,我需要计算队列中以相同第一个字符开头的名称的数量。我怎么做?我是 java 的新手,所以我了解的不多。

It should print the following statistics:
- The total number of country names in the queue that begins with the same letter.
- To compute the above statistics you may use other data structures, such as Array, or ArrayList/Vector.

示例:

User inputs/what is in the queue:

  1. Brazil
  2. Italy
  3. Singapore
  4. Spain
  5. Switzerland
  6. Iceland

输出:

Total number of countries start with I : 2

Total number of countries start with S : 3

我试过搜索这个,但我还没有真正找到一个可靠的方法来做到这一点。任何帮助将不胜感激。

注意:我不允许使用任何 Java 的机制,必须自己实现它

这是我到目前为止的程序。

如果您不能使用任何 Java 集合,您可以简单地创建由零填充的每个可能字符的 int 数组,然后将队列中字符串的每个第一个字符转换为 int,并递增该数组指数。类似于:

// on start of program
int[] charCounts = new int[1024];
for (int i = 0; i < charCounts.length; ++i)
{
    charCounts[i] = 0;
}

// your loop
System.out.println("List of countries visited: ");
for(int i=0; i<randNum; i++)
{
    System.out.print((i+1)+". ");
    if (!myQueue.isEmpty())
    {
        String s = (String)myQueue.dequeue();
        int charCode = Character.getNumericValue(s.charAt(0));
        ++charCounts[charCode];
    }
}

既然你说过你可以使用 ArrayList 和 String,你可以很简单地创建一个类型为 StringArrayList,让用户将国家添加到 ArrayList,然后创建循环以遍历 ArrayList 并计算指定字符出现在每个单词开头的次数。

创建 ArrayList:

ArrayList<String> countries = new ArrayList<>();

我将手动将一些国家添加到列表中,但在您的情况下,您需要让用户输入:

    listOfCountries.add("Germany");
    listOfCountries.add("Scotland");
    listOfCountries.add("England");
    listOfCountries.add("Switzerland");
    listOfCountries.add("Uganda");

然后写一个方法来计数。您将调用方法 String.charAt() 以查看它是否与您要查找的字符匹配:

private int countStartingCharacters(ArrayList<String> countries, char match){

    int counter = 0;

    for (int i = 0; i < countries.size(); i++){
        if (countries.get(i).charAt(0) == match) {
            counter++;
        }
    }

    return counter;
}

为了安全起见,我将计数方法中的所有内容都转换为小写,并添加了输入验证,仅此而已。希望对你有帮助。

您可以使用下面的代码来获取以特定字符开头的国家/地区的数量-

ArrayList<String> myList = new ArrayList<String>();
while(!myQueue.isEmpty()) {
    myList.add((String)myQueue.dequeue());
}


TreeMap<Character, Integer> counts = new TreeMap<Character, Integer>();
for(int i = 0; i < myList.size(); i++) {
    String country = myList.get(i);
    Character first = Character.toUpperCase(country.charAt(0));
    if(counts.get(first) == null) {
        counts.put(first, 0);
    }
    counts.put(first, counts.get(first) + 1);
}
//Now print the counts

TreeSet<Character> keySet = new TreeSet<Character>(counts.keySet());
Iterator<Character> iterator = keySet.iterator();
while(iterator.hasNext()) {
    Character key = iterator.next();
    System.out.println("Total number of countries start with " + key + " : " + counts.get(key));
}

编辑:带有示例的示例代码 队列 Class

import java.util.*;
public class Test {
    public static void main (String[] args) {
        Queue myQueue = new Queue(10);
        ArrayList<String> myList = new ArrayList<String>();
        while(!myQueue.isEmpty()) {
            myList.add((String)myQueue.dequeue());
        }       
        TreeMap<Character, Integer> counts = new TreeMap<Character, Integer>();
        for(int i = 0; i < myList.size(); i++) {
            String country = myList.get(i);
            Character first = Character.toUpperCase(country.charAt(0));
            if(counts.get(first) == null) {
                counts.put(first, 0);
            }
            counts.put(first, counts.get(first) + 1);
        }
        //Now print the counts
        TreeSet<Character> keySet = new TreeSet<Character>(counts.keySet());
        Iterator<Character> iterator = keySet.iterator();
        while(iterator.hasNext()) {
            Character key = iterator.next();
            System.out.println("Total number of countries start with " + key + " : " + counts.get(key));
        }
    }
}

class Queue {
        String[] items;
        int pointer = 10;
    Queue(int size) {
        items = new String[10];
        items[0]="Austria";
        items[1]= "United States";
        items[2]="Nepal";
        items[3]="Bhutan";
        items[4]="China";
        items[5]="Brazil";
        items[6]="Africa";
        items[7]="Sri Lanka";
        items[8]="Italy"; 
        items[9]="India";
    }
    Object dequeue() {
        pointer--;
        return items[pointer];
    }
    boolean isEmpty() {
        return pointer == 0;
    }   
}

您可以在队列 class 中实现一个方法,给定一个字母,它 returns 队列中以该字母开头的名字的数量:

public int countriesWith(char c){
    int counter = 0;
    for(int i = 0; i < items.length; i++){
        if(items[i].startsWith(String.valueOf(c))){
            counter++;
        }
    }
    return counter;
}

你可以通过简单的way.Try解决这个问题:

  public static void main(String[] args) {
    List<String> listNames = new ArrayList<>();
    listNames.add("Austria");
    listNames.add("Russia");
    listNames.add("Brasil");
    listNames.add("Argentina");
    listNames.add("Ukraine");
    listNames.add("Belarus");
    listNames.add("Litvia");
    listNames.add("Livia");
    listNames.add("Italia"); 

    Map<String, Integer> nameCount = new HashMap<>();

    for (int i = 0; i < listNames.size(); i++) {
        int count = 0;
        for (int j = 0; j < listNames.size(); j++) {
            if (listNames.get(i).substring(0, 1).equals(listNames.get(j).substring(0, 1))) {
                ++count;
            }
        }
        nameCount.put(listNames.get(i).substring(0, 1), count);
     }
    // output
    for (Map.Entry<String, Integer> set : nameCount.entrySet()) {
        System.out.println(set.getKey() + " : " + set.getValue());
    }

}