简体   繁体   English

如何计算队列中一个单词的字母数量?

[英]How do i count the amount of letters from a word that is from a Queue?

So I am given a problem in which i have to find the specific amount of letters in a word that is from a queue, for example an apple has 2 letter p's, so i would have to print out eg "The total amount of letters in the word that start with p:2". 因此,我遇到一个问题,我必须从队列中找到单词中特定数量的字母,例如,一个苹果有2个字母p,因此我必须打印出“以p:2开头的单词”。 After that, i have no idea how to print out and count the specific letters. 在那之后,我不知道如何打印和计算特定字母。 My teacher has recommended me to use the arraylist method to count the letters, but i still do not know how to do it. 我的老师建议我使用arraylist方法对字母进行计数,但是我仍然不知道该怎么做。 Forgive me if my codes look messy, i am still quite new to programming. 如果我的代码看起来很乱,请原谅我,我还是编程新手。 Here are some of my codes so far: 到目前为止,这是我的一些代码:

package fruits;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.*;

public class Fruits {

    public static void main(String[] args) {
        Queue myQueue = new Queue(80);
        for (int j = 0; j < num; j++) {
            System.out.println("Enter the fruits you like to eat" + j + ":");
            String input = sc.nextLine();
            myQueue.enqueue(input);//enqueue the fruits

        }
        System.out.println("List of Fruits i like to eat: ");                     
        for (int x = 0; x < num; x++) {
            System.out.print(x);
            if (!myQueue.isEmpty()) {
                String input = (String) myQueue.dequeue();
                System.out.println(input);
            }
        }

        ArrayList<Queue> list = new ArrayList<Queue>();
        list.add(myQueue);
        System.out.println("Fruits that start with a letter p:");
    }
}

如果HashMap中已经存在Key,则使用HashMap<String,Integer>和Increment count

as this is homework, here are some hints: 由于这是家庭作业,因此有一些提示:

  • take care to Queue usage: you can either put things inside or pop them only once . 注意Queue使用:您可以将事物放入内部或弹出一次 Therefore, myQueue is empty when you do the second for loop (for printing them). 因此,当您进行第二次for循环(用于打印它们)时, myQueue为空。 That could give you a hint on why an ArrayList would be useful. 这可以给您提示为什么ArrayList有用。
  • As you know how to loop over items from a Queue , you just need to count the letters, word after word, and keep track of it. 正如您知道如何从Queue遍历项目一样,您只需要对字母,单词和单词进行计数,并对其进行跟踪。 Answer from rupesh_padhye gives you a good way to do it. rupesh_padhye的回答为您提供了一个很好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM