在java中添加和表示带星号的字符

在java中添加和表示带星号的字符,java,chars,Java,Chars,我有一个任务,我需要创建一个程序来读取用户输入和句子,最后它需要用星号表示每个字符重复的次数 到目前为止,这是我完成此任务的所有代码: import java.util.Scanner; public class Chars { public static void main (String[] args){ Scanner teclado = new Scanner(System.in); System.out.println("insere um texto

我有一个任务,我需要创建一个程序来读取用户输入和句子,最后它需要用星号表示每个字符重复的次数

到目前为止,这是我完成此任务的所有代码:

    import java.util.Scanner;

    public class Chars {
public static void main (String[] args){
    Scanner teclado = new Scanner(System.in);
    System.out.println("insere um texto");
    String teutexto = teclado.nextLine();
    int a = 0;
    for(int x=0;x<teutexto.length();x++){
        if( String.charAt(0) == 'a'){

        }

    }
import java.util.Scanner;
公共类字符{
公共静态void main(字符串[]args){
扫描仪teclado=新扫描仪(System.in);
System.out.println(“插入文本”);
字符串teutexto=teclado.nextLine();
int a=0;

对于(int x=0;x这是一种使用bucket排序的简单方法。您只需为字母表中的每个字符保留一个整数数组,并在输入字符串中每次出现该字符时增加它们

我们知道,
(int)'a'=97
(int)'b'=98
等等。因此,将
(a,b,…,z)
表示为
(0,1,…,25)
的一个小技巧是为给定的字符
ch
设置
(int)(ch-'a')
。因此,我们用
97
减去
ch
的值。例如:
(int)('a'-/code>)=0和
(int)('z'-'a')=25

现在,我们可以很容易地创建一个数组
int[]occurrents=new int[26]
,其中
occurrents[i]
将是字母表中第i个字符的出现次数

例如,在字符串
“aaab”
中,运行算法后:

事件[0]=3
事件[1]=1

这和

出现次数['a'-'a']=3次
出现次数['b'-'a']=1次

如果您理解了这个概念,您将看到我们可以简单地循环输入字符串,对于每个字符
ch
,我们可以增加
出现次数[ch-'a']+
。这就是整个算法

以下是完整代码:

Scanner input = new Scanner(System.in);
String str = input.nextLine().toLowerCase();

int[] occurrences = new int[26];

// go through all the characters in the input string
for(char ch : str.toCharArray())
    if(ch >= 'a' && ch <= 'z') // 'ch' is a valid character in the alphabet
        occurrences[ch-'a']++; // increase the occurrence of 'ch'

// go through the the alphabet
for(int i = 0; i < 26; i++) {
    System.out.print((char)('a'+i) + ": "); // print the i-th character in the alphabet
    // occurrences[i] contains the number of occurrences of the i-th character
    for(int j = 0; j < occurrences[i]; j++)
        System.out.print("*"); // print '*' for every occurrance of the i-th character
    System.out.println(); // separate with new line
}
input.close(); // close scanner
扫描仪输入=新扫描仪(System.in);
String str=input.nextLine().toLowerCase();
int[]出现次数=新int[26];
//检查输入字符串中的所有字符
for(字符ch:str.toCharArray())

如果(ch>='a'&&ch在什么之前?Closevotes?我们期待您的努力。我们不会为您编写代码。如果您尝试过-向我们展示您到目前为止所编写的内容以及您有哪些具体问题。感谢您解答我的问题。我将复习它,直到完全理解为止it@user3002929我编辑了。现在更详细的解释!