Computer Question (intermediate)-output the frequency of occurrence of the specified symbol in decimal form (Java)

Source: Internet
Author: User

Computer Question (intermediate)-output the frequency of occurrence of the specified symbol in decimal form (Java)

The questions are as follows:

The Code is as follows:

 

Package huawei; import java. math. bigDecimal; public final class Demo {/** function: count the frequency of occurrence of a specified character in the input benchmark string. The string only contains uppercase and lowercase letters, spaces, commas (,), and periods. after the decimal point, two valid digits are retained. The third digit is rounded to the nearest digit. ** enter: string pString input benchmark String char c specified character ** return: output frequency of the specified character */public static float getRateFromString (String pString, char c) {int num = 0; char pChar [] = pString. toCharArray (); for (int I = 0; I <pChar. length; I ++) {if (pChar [I] = c) {num ++ ;}} BigDecimal B = new BigDecimal (float) num/pChar. length); float f1 = (float) B. setScale (2, BigDecimal. ROUND_HALF_UP ). doubleValue (); // retain two decimal places return f1 ;}}
Note that the Division should be forcibly converted to float first, otherwise the precision may be lost, which is incorrect. In addition, there are many ways to retain two decimal places.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.