*Java*
If the entered number is contained in the entered text, return how many times it is there. Otherwise, return 0.
public static int countingNumber(int number, String text) {
//Your answer here. Edit the assignment and return statement as necessary//
int count = 0;
return count;
} //end countingNumber
Here is the complete code with comments
public class temp {
public static int countingNumber(int number, String text) {
int count = 0;
// First we will convert the integer to string so that we can compare it with
// the text
String comp = Integer.toString(number);
// len will keep the length of the number
int len = comp.length();
// Now we run the loop to check how many time the number appears in the string
for (int i = 0; i < text.length() - len + 1; i++) {
// the substring funtion will convert the string to a substring
// substring(a,b) means from [a,b) a index is inclusive and b is exclusive
// we use .equals function to check if comp and the substring is equal, if they
// are then we do count++
if (text.substring(i, i + len).equals(comp))
count++;
}
return count;
} // end countingNumber
// This is the main function
public static void main(String[] args) {
System.out.println(countingNumber(12, "ra21hu1as121233124312"));
}
}
Here is the code image to help understand the indentation
Here is the output for the above code
The code has been tested on different inputs too and it works perfactly.
NOTE: If you like a answer a thumbs up would make my day :)
Have a nice day
Get Answers For Free
Most questions answered within 1 hours.