【问题标题】:How to count the number of a user entered character in an array?如何计算用户在数组中输入的字符数?
【发布时间】:2020-04-24 19:09:57
【问题描述】:

我有一个 Java 任务,我需要读取一个字符,然后计算该字符在数组中出现的次数。这是我目前所拥有的。

import javax.swing.JOptionPane;

public class ArraySring
{   
    public static void main(String args[])
    {
        String userChar;

        userChar = JOptionPane.showInputDialog("Enter a character");


        String dow[] = {
                        "Monday",
                        "Tuesday",
                        "Wednesday",
                        "Thursday",
                        "Friday",
                        "Saturday",
                        "Sunday"
                       };

        for(int x=0; x<7; x++) {
            System.out.println(dow[x]);
        }
        System.out.println();
    }
} // end ArrayStrings

【问题讨论】:

  • 所以您想知道userChardow 数组中出现的频率?
  • 我希望用户通过 JOptionpane 输入一个字符,然后查看该字符在数组中出现的频率。

标签: java


【解决方案1】:

避免char

避免使用char 类型,因为它现在是legacy。该类型是在Unicode 扩展超出其原始64K limit 之前发明的。 Unicode 现在定义了两倍多的字符:Unicode 13 中有 143,859 个字符。因此,当遇到来自 Basic Multilingual Plane 之外的字符(大约是前 64,000 个字符)时,使用char 将失败

使用代码点

在现代 Java 中,我们应该使用 code point 数字而不是 char 值。

例如,让我们假设在拼写某些星期几的名称时使用了表情符号字符 FACE WITH MEDICAL MASK。愚蠢,但适合演示。 Unicode 中的该字符分配给代码点 128,567。

此代码使用IntStreamStreams 是在 Java 中表示一系列值的另一种方式。作为一个学习 Java 的初学者,现在对你来说并不重要。只要知道我们可以通过调用string.codePoints().toArray(),从流提供的一系列值中创建一个数组。我们最终得到一个int 整数数组。每个int 整数是String 文本中字符的代码点。

String userCharacter = "?";
String strings[] = { "M?nday" , "Tuesd?y" , "Wednesday" };

int count = 0;
for ( String string : strings )                                                          // Loop through the day-of-week names.
{
    IntStream codePoints = string.codePoints();                                          // Get a stream of `int` integer numbers, the Unicode code point number for each character in the string.
    int[] ints = codePoints.toArray();                                                   // Convert stream to an array.
    for ( int i : ints )                                                                 // Loop through each number, each code point.
    {
        System.out.println( "i  = " + i + " character: " + Character.toString( i ) );    // Debugging. Dump values to the console.
        if ( i == userCharacter.codePointAt( 0 ) )                                       // Compare this nth number (the code point of the nth character in the day-of-week name) against the code point number of the character given by the user.
        {
            System.out.println( "Hit.") ;                                                // Debugging.
            count++;                                                                     // If they match, increment our counter.
        }
    }
}

转储到控制台。

System.out.println( "count = " + count );                                                // Dump to console.
System.out.println( "userCharacter.codePointAt( 0 ): " + userCharacter.codePointAt( 0 ) );

运行时。

i  = 77 character: M
i  = 128567 character: ? 
Hit.
i  = 110 character: n
i  = 100 character: d
i  = 97 character: a
i  = 121 character: y
i  = 84 character: T
i  = 117 character: u
i  = 101 character: e
i  = 115 character: s
i  = 100 character: d
i  = 128567 character: ?
Hit.
i  = 121 character: y
i  = 87 character: W
i  = 101 character: e
i  = 100 character: d
i  = 110 character: n
i  = 101 character: e
i  = 115 character: s
i  = 100 character: d
i  = 97 character: a
i  = 121 character: y
count = 2
userCharacter.codePointAt( 0 ): 128567

有关详细信息,请参阅:

【讨论】:

  • 谢谢!很高兴知道!我不知道这个
【解决方案2】:

给你:

public static void main(String args[]) {
    char userChar = JOptionPane.showInputDialog("Enter a character").toLowerCase().charAt(0);
    int count = 0;
    String dow[] = // ...

    for (String str : dow)
        for (char ch : str.toLowerCase().toCharArray())
            if (ch == userChar)
                count++;

    System.out.println(count);
}

【讨论】:

【解决方案3】:

Basil 的回复很好,感谢您的全面描述。接受 Basil 关于使用代码点而不是字符的建议,除此之外,使用一些流处理也将解决方案转换为:

public static void main(String args[]) {
        int inputCodePoint = JOptionPane.showInputDialog("Enter a character").toLowerCase().codePointAt(0);
        String dow[] = {
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
        };

    System.out.println(Arrays.stream(dow)
                             .flatMap(s -> Arrays.stream(s.split("")))
                             .filter(s -> s.equals(Character.toString(inputCodePoint)))
                             .count());
}

这利用了Character.toString(int)添加在JDK 11中。

【讨论】:

    猜你喜欢
    • 2020-04-01
    • 2015-04-21
    • 2015-01-21
    • 2023-04-08
    • 2021-03-04
    • 1970-01-01
    • 2014-12-30
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多