How to Calculate the Percentage of Characters in Java
Java lets you perform calculations to determine the number of characters you have in one string compared to another. You divide a string's length of characters by your main string's length to determine the percentage of characters used in the first string. Programmers use this type of function to test that users have entered the proper percentage of characters in an input field.
Instructions
-
-
1
Right-click your Java file and click "Open With." Select your Java editor from the list of programs.
-
2
Create the strings, if you do not already have two strings set up in your code.. The following code shows you how to create two strings in Java:
string string1 = "my code";
string string2 = "this is the second string"; -
-
3
Get the length of the two strings that you want to use in your calculations. The following code gets the length of the strings created in step 2:
int length1 = string1.length();
int length2 = string2.length(); -
4
Calculate the percentage of characters. The following code calculates the character percentage of string 1 in comparison to string 2:
int percentage = length1/length2;
-
1