有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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检查字符串中的字符

enter image description here

Expected outcome

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 + " | ");      
}

共 (1) 个答案

  1. # 1 楼答案

    用地图记录你的信件和计数。如果使用TreeMap,默认情况下它将按键排序。因此,之前不需要对字符进行排序

        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
        }