首页 > 解决方案 > 信件计数应用程序

问题描述

package jdaprogrammingactivity22;

/*
 *@Title: JDAProgrammingAssignment4
 *@Description:  Create a program the will count and display a table
 * showing occurrence of each letter in the inputted word/phrase/sentence. 
 * The letters should be sorted in alphabetical order
 *
 * @author Jan Dierekh B. Arroyo
 * Date: Created: July 28, 2019
 *
 */


import java.util.*;
import static java.lang.System.*;


public class JDAProgrammingActivity22 {


static void header()
{
     String s = "LETTER COUNTING APPLICATION";
     out.println(s);
     for(int i = 0; i < s.length(); i++)
     {
         out.print("-");
     }
     out.println();

} 


static void input()
{
   Scanner scan = new Scanner(System.in);

   out.print("Enter a word/phrase/sentence: ");
   String str1 = scan.nextLine();
   toUpCase(str1);

   out.println(">> Unique Letters:");
   String sort = sortStr(str1);

   out.println("Sorted String: " + sort);

   uniqueLetter(sort);

} 

static String sortStr(String str1)
{ 
    char tempArray[] = str1.toCharArray(); 
        Arrays.sort(tempArray); 

   return new String(tempArray);         
}


static void toUpCase(String str1)
{
    str1 = str1.toUpperCase();
    out.println(">> Word/Phrase/Sentence: ");
    out.println("\t" + str1 + "\n");
}       

static void uniqueLetter(String str1)
{
    int num = 0,COUNT = 0;
    String line = "\t+-----+--------+-------+";
    out.println(line);
    out.println("\t| NO. | LETTER | COUNT | ");
    out.println(line);

    String[] words = str1.split("\\s+");

    for (String word : words) {
        out.println("\t| " + num + " |" + word  + " | " + COUNT + " | ");
    }  

}        

    public static void main(String[] args) {

        header();

        input();




    }

}

我正在制作一个程序,它将计算并显示一个表格,显示输入的单词/短语/句子中每个字母的出现。字母应按字母顺序排序。

我已经对字符串进行了排序并将其更改为大写,因为它是必需的,并且我已经有了一个字符串出现字符的计数算法。

我的问题是关于期望的输出,你可以看看预期的结果。我不知道如何将它输出到桌子上并放置角色。请帮忙。

我已经尝试使用 switch 检查每个字符,但我不知道如何使用 switch 检查字符串中的字符。

在此处输入图像描述

预期结果

int num,count;
char letter;

String line = "\t+-----+--------+-------+";
out.println(line);
out.println("\t| NO. | LETTER | COUNT | ");
out.println(line);

for(int i = 0; i >= str1.length(); i++)
{
 out.println("\t| " + num + " |" + LETTER + " | " + COUNT + " | ");      
}

标签: javastringchar

解决方案


为您的字母和计数使用地图。如果使用 a TreeMap,则默认按 key 排序。所以你不需要在之前对字符进行排序。

    Map<Character, Integer> map = new TreeMap<>();
    for (Character ch : str1.toUpperCase().toCharArray()) {
       Integer count = map.getOrDefault(ch, 0);
       map.put(ch, count + 1);
    }
    int no = 0;
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
       no ++;
       Character ch = entry.getKey();
       Integer count = entry.getValue();
       // output your values here
    }

推荐阅读