【问题标题】:Occurrences of each letter每个字母的出现次数
【发布时间】:2013-07-11 13:42:19
【问题描述】:

这是我必须编写的程序,但出现此错误,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
50

用两个数组写一个完整的程序,upper和lower保持upper 和小写字母分别。 要求用户输入字符串示例:

这是来自木星的测试。很快你就会看到谁来自 木星!!!可能是D博士。

您的程序应该解析字符串并跟踪字母的数量。两个数组的索引都是从 0 到 25。这样做的逻辑方法是使用 upper[0] 来 计算‘A’的个数,用upper[1]计算‘B’的个数,以此类推。同样地 对于较低的数组。

输出应如下所示:

A: 0 a:2

B: 0 b:0
.
.
.
Z:0 z:0

代码

import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;

public class Letter {
  public static void main(String[] args) {

    // this is get results
    char[] chars = userEnters();

    System.out.println();
    System.out.println("Occurrences of each letter are:");
    PrintArray(countLow(chars), countUp(chars));
  }

  public static char[] userEnters() {

    String inputX = JOptionPane.showInputDialog("Enter line of text:  ");
    char[] chars = inputX.toCharArray();

    return chars;
  }

  public static int[] countLow(char[] input) {
    int[] counts = new int[26];

    for (int i = 0; i < input.length; i++) {
      counts[input[i] - 'a']++;
    }
    return counts;
  }

  public static int[] countUp(char[] input2) {
    int[] countsUp = new int[26];
    for (int i = 0; i < input2.length; i++) {
      countsUp[input2[i] - 'A']++;
    }
    return countsUp;
  }

  public static void PrintArray(int[] counts, int[] countsUp) {
    for (int i = 0; i < counts.length; i++) {

      System.out.print(counts[i] + " " + (char) ('a' + i) + " ");
      System.out.print(countsUp[i] + " " + (char) ('A' + i) + "\n");
    }
  }
}

【问题讨论】:

  • 你得到了什么输出?
  • 当您在countLow 并且 input[i] 是大写字母时,您认为会发生什么?
  • 您可能希望过滤掉“无效”字符,例如 !、` ` 和 .,因为它们的代码点不在 a-zA-Z 内。
  • 正如其他人所说:在计算小写/大写字母之前,您必须确保它实际上是小写/大写字母。

标签: java string search


【解决方案1】:

如果输入的字符不是大写,countUp 会抛出异常,如果输入的字符不是小写,countLow 会抛出异常。

示例:如果您在 A 上调用 countLow,则计算 'A' - 'a',它会返回 -32,并且不允许使用负索引。

您需要检查您的逻辑并根据字母的大小写调用 countLow 或 countUp 并过滤掉无效字符。 或者重构整个东西并使用char[52],例如你可以同时持有大小写。

【讨论】:

  • OP 也不适合特殊字符。他使用“.”、“”和“!”至少。请使用此信息更新您的答案,另一个答案是没有根据的。
【解决方案2】:

我希望你不介意我确实重构了你的代码。

请查看此问题的替代解决方案,然后阅读答案底部的 cmets。

   import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.JOptionPane;


public class LetterCounter {

    //Hash maps don't allow duplication. 
    //The letter will be the Key and the repetitions the value(Your goal!)
    private Map<Character, Integer> resultsMap = new HashMap<Character, Integer>(); 

    public static void main(String[] args) {

        LetterCounter letterCounter = new LetterCounter();
        letterCounter.fillMap();
        letterCounter.showMapContents();        
    }

    private void showMapContents() {
        for (Entry<Character, Integer> entry : resultsMap.entrySet())
        {
            System.out.println("'" + entry.getKey() + "' - " + entry.getValue() + " times");
        }       
    }

    private void fillMap() {
        char[] userInputAsArray = getUserInputAsLetterArray();
        for (int currentLetter = 0; currentLetter < userInputAsArray.length; currentLetter++) {
            int count = getOccurences(userInputAsArray[currentLetter],userInputAsArray);
            resultsMap.put(userInputAsArray[currentLetter], count);
        }
    }

    private int getOccurences(int letter, char[] userInputAsArray) {
        int counter = 0;
        for (int currentIndex = 0; currentIndex < userInputAsArray.length; currentIndex++) {
            if(userInputAsArray[currentIndex] == letter)
                counter++;
        }
        return counter;
    }

    public char[] getUserInputAsLetterArray() {
        String userInput = JOptionPane.showInputDialog("Enter line of text:  ");
        char[] chars = userInput.toCharArray();
        return chars;
    }
}
  • 无论何时您想要进行需要操作数据的练习,您都应该选择最适合该工作的数据结构。在您的情况下,我认为哈希映射可能会很有趣,因为它避免了重复并且将为您完成大部分工作。在此链接中找到一个非常好的备忘单:http://www.janeve.me/articles/which-java-collection-to-use
  • 我注意到你使用了很多静态的,这不是一个非常面向对象的事情。作为一种替代方法,当您只想在运行中做一些类似这样的快速示例时,您可以在其内部初始化类。

我希望这很有用。

【讨论】:

  • 非常感谢。这是一个很好的答案。还有一件事,我如何打印所有字母,然后说出它们有多少:例如 a:0 A:0 .... z:2 Z:1
  • @Ali Ashtiani 不客气。我不知道你说的有多少是什么意思?如果您的意思是字母的总数,那很容易,您只需将地图中每个条目的值相加即可。
【解决方案3】:

您或许应该考虑从数组转移到更复杂、更强大的数据结构,例如Map&lt;Character,Integer&gt;

使用该数据结构,您需要的代码将类似于

public Map<Character,Integer> countOccurrencies(String inputString){
    Map<Character,Integer> occurrencies = new HashMap<Character,Integer>();
    for(Character c : inputString){
        if(occurrencies.containsKey(c)){
            occurrencies.put(c, occurrencies.containsKey(c) + 1);
        } else {
            occurrencies.put(c, 1);
        }
    }
    return occurrencies;
}

【讨论】:

    【解决方案4】:

    用java回答:

    这里,countOfOccurances("pppggggkkkkpgaaaa") 为您提供字符串中每个字符的出现次数

       public static void countOfOccurances(String mainStr)
              {
                String temp = "";       
                for (int i = 0 ; i < mainStr.length();i++)
                {
                CharSequence ch = String.valueOf(mainStr.charAt(i));
                temp=mainStr.replace(ch, "");
                int count = (mainStr.length()-temp.length());
                System.out.println(ch+" = "+count);         
                mainStr = temp; 
                i = -1;
              }
              }
    

    方法的输出:

    p = 4
    g = 5
    k = 4
    a = 4
    

    【讨论】:

      猜你喜欢
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多