java - 信件计数应用程序
问题描述
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 + " | ");
}
解决方案
为您的字母和计数使用地图。如果使用 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
}
推荐阅读
- python - 在 Python 中使用 mysqldb 连接 ipv6 服务器
- c++ - MSYS2 和 Windows 运行时库
- hana - 计算视图的 HANA Studio 作业计划
- powerbi - Power BI - 滚动平均值
- python - 在 mqtt 消息中发送元数据
- facebook - Facebook 导出 API 的替代方案
- eclipse - 如何在 Eclipse 中包含过滤文件夹中的单个资源
- c# - 在对象向量中引用对象
- html - 我正在尝试在 JSP 中将一个月添加到当前月份并在 html 教科书中显示结果
- python - 运行 python 脚本时的 Crontab 日志数据