0

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

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

编写一个完整的程序,使用两个数组,上和下分别保留上下字母。要求用户输入字符串示例:

这是来自木星的测试。很快你就会看到谁来自木星!!!可能是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");
    }
  }
}
4

4 回答 4

7

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

示例:如果您调用countLowa A,您将计算'A' - 'a'哪些返回-32并且不允许使用负索引。

您需要检查您的逻辑并根据字母的大小写调用 countLow 或 countUp 并过滤掉无效字符。或者重构整个事情并使用一个char[52]例子,你同时持有小型和大型资本。

于 2013-07-11T13:46:00.357 回答
1

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

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

   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
  • 我注意到你使用了很多静态的,这不是一个非常面向对象的事情。作为一种替代方法,当您只想在运行中做一些像这样的快速示例时,您可以在其内部初始化类。

我希望这很有用。

于 2013-07-11T14:21:30.790 回答
0

用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
于 2014-02-01T11:45:37.040 回答
0

您可能应该考虑从数组转移到更复杂和更强大的数据结构,例如Map<Character,Integer>.

使用该数据结构,您需要的代码看起来像

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;
}
于 2013-07-11T14:01:47.693 回答