【问题标题】:How do i count the amount of letters from a word that is from a Queue?我如何计算来自队列的单词的字母数量?
【发布时间】:2016-01-07 13:27:12
【问题描述】:

所以我遇到了一个问题,我必须在来自队列的单词中找到特定数量的字母,例如一个苹果有 2 个字母 p,所以我必须打印出例如“总金额单词中以 p:2" 开头的字母。在那之后,我不知道如何打印和计算特定的字母。我的老师建议我使用 arraylist 方法来计算字母,但我仍然不知道该怎么做。如果我的代码看起来很乱,请原谅我,我对编程还是很陌生。 到目前为止,这是我的一些代码:

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:");
    }
}

【问题讨论】:

    标签: java arraylist queue


    【解决方案1】:

    使用HashMap&lt;String,Integer&gt; 并在 HashMap 中已经存在 Key 时增加计数

    【讨论】:

      【解决方案2】:

      因为这是作业,这里有一些提示:

      • 注意Queue 的用法:您可以将东西放入其中,也可以将它们弹出一次。因此,当您执行第二个 for 循环(用于打印它们)时,myQueue 为空。这可以给你一个提示,为什么 ArrayList 会有用。
      • 正如您知道如何循环遍历来自Queue 的项目,您只需要逐字计算字母并跟踪它。 rupesh_padhye 的回答为您提供了一个很好的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-02-21
        • 2016-08-13
        • 1970-01-01
        • 1970-01-01
        • 2022-06-21
        • 2014-04-30
        • 2022-12-11
        相关资源
        最近更新 更多