java - 每个字母出现的次数

标签 java string search

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

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

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

This is a test from Jupiter. Soon you will see who is from Jupiter!!! May be Dr. 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");
    }
  }
}

最佳答案

如果您输入的字符不是大写字母,countUp 将抛出异常,如果您输入的字符不是小写字母,countLow 将抛出异常一个异常(exception)。

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

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

关于java - 每个字母出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17595012/

相关文章:

Java伪定时器

java - Apache Tomcat : "Context variable"

java - 如何创建动态大小的 JScrollPane w/JPanel 作为客户端?

java - 读取 ArrayList 的一部分 n 行?

java - 将控制台的 while 循环输出写入 java 中的文本文件

java - 分割从 Json 响应收到的字符串

string - 在忽略大小写的情况下比较字符串的有效方法是什么?

java - 使用 Java 和 Scribe 的 Vimeo 搜索 API

Java:根据某个字段获取大量对象List的最高效组合

c - 在最坏的情况下,在排序的链表中搜索一个元素需要进行多少次比较?