gpt4 book ai didi

java - 如何对字符串中的字母进行计数和排序

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:40:53 24 4
gpt4 key购买 nike

我想对用户输入的字母进行排序,并打印出用户输入的字符串中每个字母的数量。这是我到目前为止所拥有的,我想知道这是否是正确的方法。我是 java 的新手,所以请尽可能简单。我根据使用循环而不是大量 if else 结构的建议对我的代码进行了一些调整。这是我的:

public class Assignment9
{
public static void main( String [] args )
{
String user_string = Input.getString( "Please enter a string" );
int length = user_string.length();
int char_number = 1;
int alphabet[] = new int[26];
for( int repeats = 0 , repeats <= length , repeats++ )
{
char letter = user_string.charAt( char_number );
char to_be_tested = Character.toLowerCase( letter );
int subscript = 0;
for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
{
char tester = (char) letter_number;

if( to_be_tested == tester )
{
alphabet[subscript]++;
subscript++;
}
}
char_number++;
}
display( alphabet );
}
public static void display( int alphabet[] )
{
int letter = 65;
for( int a = 0; a < alphabet.length; a++ )
{
char character = ( char )letter;
System.out.println ( "letter " + character + " count is " + alphabet[a] );
letter++;
}
}
}

我遇到了这些错误

Compilation errors :

test.java:9: error: ';' expected
for( int repeats = 0 , repeats <= length , repeats++ )
^
test.java:9: error: illegal start of expression
for( int repeats = 0 , repeats <= length , repeats++ )
^
test.java:9: error: ';' expected
for( int repeats = 0 , repeats <= length , repeats++ )
^
test.java:9: error: illegal start of expression
for( int repeats = 0 , repeats <= length , repeats++ )
^
test.java:9: error: ')' expected
for( int repeats = 0 , repeats <= length , repeats++ )
^
test.java:9: error: illegal start of expression
for( int repeats = 0 , repeats <= length , repeats++ )
^
test.java:14: error: ';' expected
for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
^
test.java:14: error: illegal start of expression
for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
^
test.java:14: error: ';' expected
for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
^
test.java:14: error: illegal start of expression
for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
^
test.java:14: error: ')' expected
for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
^
test.java:14: error: illegal start of expression
for(int letter_number = 97 , letter_number <= 122 , letter_number++ )
^
12 errors

最佳答案

这里有一个更简单的计算字母的方法,忽略大小写:

final int[] chars = new int[26];
for (char c : value.toLowerCase().toCharArray()) {
if ((c >= 'a') && (c<= 'z')) {
chars[c - 'a']++;
}
}

演示:https://repl.it/CmYR/0

关于java - 如何对字符串中的字母进行计数和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38912960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com